getElementById() |
Holt ein Element nach seiner ID. |
document.getElementById("demo").innerText = "Hallo!"; |
Erstelle eine Webseite, die ein div-Element enthält und den Text dieses Elements mit getElementById zu "Hallo Welt!" ändert. |
Zugriff auf spezifische Elemente für Manipulation, Event-Handling usw. |
querySelector() |
Holt das erste Element, das dem angegebenen Selector entspricht. |
document.querySelector(".demo-class").style.color = "blue"; |
Entwickle eine HTML-Seite, die ein Element mit der Klasse demo-class nutzt und die Farbe dieses Elements mit querySelector auf Blau setzt. |
Auswahl und Manipulation von DOM-Elementen. |
addEventListener() |
Fügt einem Element ein Ereignis-Listener hinzu. |
document.getElementById("btn").addEventListener("click", function() { alert("Geklickt!"); }); |
Generiere eine einfache HTML-Seite mit einem Button, der beim Klicken eine Alert-Box anzeigt, implementiert mit addEventListener. |
Hinzufügen von interaktiven Funktionen zu Webseiten. |
setTimeout() |
Führt Code nach einer festgelegten Zeit aus. |
setTimeout(function() { alert("Zeit abgelaufen!"); }, 3000); |
Erstelle eine HTML-Seite, die eine Funktion verwendet, um nach drei Sekunden eine Benachrichtigung anzuzeigen, realisiert durch setTimeout. |
Verzögerte Ausführung von Code in Webanwendungen. |
fetch() |
Macht Netzwerkanfragen, z.B. für APIs. |
fetch('https://api.example.com/data').then(response => response.json()).then(data => console.log(data)); |
Entwickle eine Web-App, die Daten von einer API abruft und diese im Browser anzeigt, verwendet fetch. |
Abrufen von Daten aus dem Netzwerk. |
Array.forEach() |
Führt eine Funktion für jedes Element eines Arrays aus. |
[1, 2, 3].forEach(num => console.log(num)); |
Schreibe ein Skript in einer HTML-Seite, das ein Array durchläuft und jeden Wert in der Konsole ausgibt, nutzt Array.forEach. |
Iteration über Arrays für Datenmanipulation und -anzeige. |
JSON.parse() |
Wandelt einen JSON-String in ein Objekt um. |
let obj = JSON.parse('{"name":"Max"}'); |
Implementiere ein Skript in HTML, das eine JSON-kodierte Zeichenkette in ein JavaScript-Objekt umwandelt, verwendet JSON.parse. |
Umwandlung von JSON-Daten in nutzbare JavaScript-Objekte. |
JSON.stringify() |
Wandelt ein Objekt in einen JSON-String um. |
let jsonStr = JSON.stringify({name: "Max"}); |
Erstelle eine Funktion in einer HTML-Seite, die ein JavaScript-Objekt in einen JSON-String konvertiert, verwendet JSON.stringify. |
Erzeugung von JSON-Strings aus JavaScript-Objekten. |
Math.random() |
Erzeugt eine zufällige Zahl zwischen 0 und 1. |
let zufallszahl = Math.random(); |
Generiere eine HTML-Seite mit einem Skript, das bei jedem Laden der Seite eine zufällige Zahl anzeigt, nutzt Math.random. |
Erstellung von Zufallszahlen für Spiele oder Simulationen. |
Array.map() |
Erstellt ein neues Array mit den Ergebnissen der Aufrufung einer Funktion für jedes Element. |
[1, 2, 3].map(num => num * 2); |
Erstelle ein Skript in HTML, das ein Array von Zahlen nimmt und jedes Element verdoppelt, zeigt das Ergebnis an, verwendet Array.map. |
Transformation von Array-Daten. |
Array.filter() |
Creates a new array with all elements that pass the test implemented by the provided function. |
[1, 2, 3].filter(num => num > 1); |
Create a script that filters an array of numbers to only include those greater than a certain value, uses Array.filter. |
Filtering data in arrays. |
Array.reduce() |
Executes a reducer function (that you provide) on each element of the array, resulting in a single output value. |
[1, 2, 3].reduce((acc, num) => acc + num, 0); |
Implement a script that calculates the sum of all numbers in an array, uses Array.reduce. |
Reducing array data to a single value. |
String.replace() |
Replaces a specified value with another value in a string. |
'Hello World'.replace('World', 'AI'); |
Create a script that replaces a specific word in a string with another word, uses String.replace. |
Manipulating string data. |
Date.now() |
Returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. |
let now = Date.now(); |
Implement a script that displays the current timestamp in milliseconds, uses Date.now. |
Working with time and dates. |
Object.keys() |
Returns an array of a given object's own enumerable property names. |
let keys = Object.keys({a: 1, b: 2}); |
Create a script that lists all property names of an object, uses Object.keys. |
Working with object properties. |
Object.values() |
Returns an array of a given object's own enumerable property values. |
let values = Object.values({a: 1, b: 2}); |
Implement a script that lists all property values of an object, uses Object.values. |
Working with object properties. |
Object.assign() |
Copies all enumerable own properties from one or more source objects to a target object. |
let target = {}; Object.assign(target, {a: 1}, {b: 2}); |
Create a script that merges two objects into one, uses Object.assign. |
Merging objects. |
Math.floor() |
Rounds a number downwards to the nearest integer. |
let rounded = Math.floor(4.7); |
Implement a script that rounds a decimal number down to the nearest integer, uses Math.floor. |
Rounding numbers. |
Math.ceil() |
Rounds a number upwards to the nearest integer. |
let rounded = Math.ceil(4.3); |
Create a script that rounds a decimal number up to the nearest integer, uses Math.ceil. |
Rounding numbers. |
JSON.parse() |
Parses a JSON string, constructing the JavaScript value or object described by the string. |
let obj = JSON.parse('{"name":"John"}'); |
Implement a script that converts a JSON string to a JavaScript object, uses JSON.parse. |
Working with JSON data. |
Array.some() |
Tests whether at least one element in the array passes the test implemented by the provided function. |
[1, 2, 3].some(num => num > 2); |
Create a script that checks if any number in an array is greater than a certain value, uses Array.some. |
Checking conditions in arrays. |
Array.every() |
Tests whether all elements in the array pass the test implemented by the provided function. |
[1, 2, 3].every(num => num < 5); |
Implement a script that checks if all numbers in an array are less than a certain value, uses Array.every. |
Checking conditions in arrays. |
String.indexOf() |
Returns the first index at which a given element can be found in the array, or -1 if it is not present. |
'Hello World'.indexOf('World'); |
Create a script that finds the position of a specific word in a string, uses String.indexOf. |
Working with string data. |
String.slice() |
Extracts a section of a string and returns a new string. |
'Hello World'.slice(6); |
Implement a script that extracts a part of a string starting from a specific position, uses String.slice. |
Manipulating string data. |
String.toUpperCase() |
Converts a string to uppercase letters. |
'hello'.toUpperCase(); |
Create a script that converts a string to all uppercase letters, uses String.toUpperCase. |
Manipulating string data. |
String.toLowerCase() |
Converts a string to lowercase letters. |
'HELLO'.toLowerCase(); |
Implement a script that converts a string to all lowercase letters, uses String.toLowerCase. |
Manipulating string data. |
Number.isNaN() |
Determines whether a value is NaN or not. |
Number.isNaN(NaN); |
Create a script that checks if a value is NaN, uses Number.isNaN. |
Checking for invalid numbers. |
Number.isInteger() |
Determines whether the passed value is an integer. |
Number.isInteger(4); |
Implement a script that checks if a value is an integer, uses Number.isInteger. |
Checking for integers. |
Number.parseFloat() |
Parses a string argument and returns a floating point number. |
let num = Number.parseFloat('4.7'); |
Create a script that converts a string to a floating point number, uses Number.parseFloat. |
Converting string to numbers. |
Number.parseInt() |
Parses a string argument and returns an integer. |
let num = Number.parseInt('4'); |
Implement a script that converts a string to an integer, uses Number.parseInt. |
Converting string to numbers. |
Array.some() |
Tests whether at least one element in the array passes the test implemented by the provided function. |
[1, 2, 3].some(num => num > 2); |
Create a script that checks if any number in an array is greater than a certain value, uses Array.some. |
Checking conditions in arrays. |
Array.every() |
Tests whether all elements in the array pass the test implemented by the provided function. |
[1, 2, 3].every(num => num < 5); |
Implement a script that checks if all numbers in an array are less than a certain value, uses Array.every. |
Checking conditions in arrays. |
String.indexOf() |
Returns the first index at which a given element can be found in the array, or -1 if it is not present. |
'Hello World'.indexOf('World'); |
Create a script that finds the position of a specific word in a string, uses String.indexOf. |
Working with string data. |
String.slice() |
Extracts a section of a string and returns a new string. |
'Hello World'.slice(6); |
Implement a script that extracts a part of a string starting from a specific position, uses String.slice. |
Manipulating string data. |
String.toUpperCase() |
Converts a string to uppercase letters. |
'hello'.toUpperCase(); |
Create a script that converts a string to all uppercase letters, uses String.toUpperCase. |
Manipulating string data. |
String.toLowerCase() |
Converts a string to lowercase letters. |
'HELLO'.toLowerCase(); |
Implement a script that converts a string to all lowercase letters, uses String.toLowerCase. |
Manipulating string data. |
Number.isNaN() |
Determines whether a value is NaN or not. |
Number.isNaN(NaN); |
Create a script that checks if a value is NaN, uses Number.isNaN. |
Checking for invalid numbers. |
Number.isInteger() |
Determines whether the passed value is an integer. |
Number.isInteger(4); |
Implement a script that checks if a value is an integer, uses Number.isInteger. |
Checking for integers. |
Number.parseFloat() |
Parses a string argument and returns a floating point number. |
let num = Number.parseFloat('4.7'); |
Create a script that converts a string to a floating point number, uses Number.parseFloat. |
Converting string to numbers. |
Number.parseInt() |
Parses a string argument and returns an integer. |
let num = Number.parseInt('4'); |
Implement a script that converts a string to an integer, uses Number.parseInt. |
Converting string to numbers. |
Promise() |
An object representing the eventual completion or failure of an asynchronous operation. |
let promise = new Promise((resolve, reject) => { /* asynchronous operation */ }); |
Create a script that performs an asynchronous operation using a Promise, resolves with the result or rejects with an error. |
Handling asynchronous operations. |
async/await |
A syntax to work with Promises in a more comfortable, synchronous-like manner. |
async function example() { let result = await promise; } |
Implement a script that uses async/await to handle Promises, making the code look synchronous. |
Handling asynchronous operations. |
Object.create() |
Creates a new object with the specified prototype object and properties. |
let obj = Object.create({}, { prop: { value: 'value', writable: true, enumerable: true, configurable: true } }); |
Create a script that creates a new object with a specified prototype and properties, uses Object.create. |
Working with object-oriented programming. |
Object.defineProperty() |
Defines a new property directly on an object, or modifies an existing property on an object. |
Object.defineProperty(obj, 'prop', { value: 'value', writable: true, enumerable: true, configurable: true }); |
Implement a script that defines a new property on an object or modifies an existing one, uses Object.defineProperty. |
Working with object properties. |
Object.freeze() |
Freezes an object, preventing any changes to its properties. |
let obj = { prop: 'value' }; Object.freeze(obj); |
Create a script that freezes an object, preventing any changes to its properties, uses Object.freeze. |
Creating immutable objects. |
Array.from() |
Creates a new Array instance from an array-like or iterable object. |
let arr = Array.from('Hello'); |
Implement a script that creates an array from a string, uses Array.from. |
Converting array-like objects to arrays. |
Symbol() |
Creates a unique and immutable primitive value that may be used as the key of an Object property. |
let sym = Symbol('description'); let obj = { [sym]: 'value' }; |
Create a script that uses a Symbol as a property key in an object, ensuring uniqueness and immutability. |
Working with unique object properties. |
Set |
An object that lets you store unique values of any type, whether primitive values or object references. |
let set = new Set([1, 2, 3, 4]); |
Implement a script that uses a Set to store unique values and perform set operations like union, intersection, and difference. |
Working with collections of unique values. |
Map |
An object that holds key-value pairs and remembers the original insertion order of the keys. |
let map = new Map([['key', 'value'], ['key2', 'value2']]); |
Create a script that uses a Map to store key-value pairs, allowing any data type for keys and maintaining insertion order. |
Working with key-value collections. |
Proxy |
An object that enables you to create a proxy for another object, which can intercept and customize fundamental operations for that object. |
let handler = { get: function(target, name) { /* custom logic */ } }; let proxy = new Proxy({}, handler); |
Implement a script that uses a Proxy to intercept and customize operations on an object, enabling advanced object manipulation. |
Creating custom object behaviors. |
Reflect |
An object that provides methods for interceptable JavaScript operations, used by Proxy handlers and available as static methods on the Reflect object. |
Reflect.get(obj, 'prop'); |
Create a script that uses Reflect methods to perform operations like getting, setting, and deleting properties, making functions constructible, and more. |
Working with interceptable JavaScript operations. |
Generators |
A special type of function that allows you to control its execution by iterating over it, using the yield keyword to pause and resume execution. |
function* generator() { yield 1; yield 2; yield 3; } |
Implement a script that uses a generator function to create an iterable object, allowing you to control its execution and return values. |
Creating custom iterables and controlling function execution. |
Async Generators |
A combination of async functions and generators, allowing you to create asynchronous iterable objects and use the yield keyword with Promises. |
async function* asyncGenerator() { yield await promise; } |
Create a script that uses an async generator function to create an asynchronous iterable object, allowing you to control its execution and return values based on Promises. |
Creating custom asynchronous iterables and controlling function execution. |
WeakSet |
A collection of unique objects, where the objects are held weakly, meaning they can be garbage collected if there are no other references to them. |
let weakSet = new WeakSet(); weakSet.add({ key: 'value' }); |
Implement a script that uses a WeakSet to store unique objects without preventing their garbage collection when there are no other references. |
Working with collections of weakly held objects. |
WeakMap |
A collection of key-value pairs, where the keys are held weakly, meaning they can be garbage collected if there are no other references to them. |
let weakMap = new WeakMap(); weakMap.set({ key: 'value' }, 'value2'); |
Create a script that uses a WeakMap to store key-value pairs without preventing the garbage collection of keys when there are no other references. |
Working with collections of weakly held key-value pairs. |
Class |
A syntax for creating objects with a constructor and prototype methods, serving as a blueprint for creating new objects. |
class MyClass { constructor() { /*...*/ } method() { /*...*/ } } |
Implement a script that uses a class to define a blueprint for creating objects with specific properties and methods. |
Working with object-oriented programming. |
Module |
A file containing JavaScript code that can be imported and exported, allowing you to organize and reuse code across different files. |
export function myFunction() { /*...*/ } and import { myFunction } from './module.js'; |
Create a script that uses modules to organize and reuse code across different files, using import and export statements. |
Organizing and reusing code with modules. |
Template Literals |
A syntax for creating strings with embedded expressions, using backticks (`) and ${expression} placeholders. |
let str = `Hello, ${name}!`; |
Implement a script that uses template literals to create strings with embedded expressions, making it easier to create dynamic strings. |
Creating dynamic strings with embedded expressions. |
Destructuring Assignment |
A syntax for extracting values from arrays or objects and assigning them to variables, making it easier to work with complex data structures. |
let [a, b] = [1, 2]; let { prop } = { prop: 'value' }; |
Create a script that uses destructuring assignment to extract values from arrays or objects and assign them to variables, simplifying code and improving readability. |
Working with complex data structures. |
Spread Operator |
A syntax for spreading the elements of an iterable object (like an array) into individual elements, or merging objects. |
let arr = [...arr1, ...arr2]; let obj = { ...obj1, ...obj2 }; |
Implement a script that uses the spread operator to spread elements of iterable objects or merge objects, simplifying code and improving readability. |
Working with arrays, iterables, and objects. |
Arrow Functions |
A shorthand syntax for declaring functions, with optional implicit return and lexical `this` binding. |
const add = (a, b) => a + b; |
Create a script that uses arrow functions to define concise and expressive functions, taking advantage of implicit return and lexical `this` binding. |
Writing concise and expressive functions. |
Rest Parameters |
A syntax for representing an indefinite number of arguments as an array, allowing you to create flexible and reusable functions. |
function sum(...numbers) { /*...*/ } |
Implement a script that uses rest parameters to create flexible and reusable functions that can handle an indefinite number of arguments. |
Creating flexible and reusable functions. |
Optional Chaining |
A syntax for accessing nested object properties without having to check if each reference in the chain is null or undefined, simplifying code and reducing errors. |
const value = obj?.prop?.nestedProp; |
Create a script that uses optional chaining to access nested object properties safely and concisely, reducing the need for null and undefined checks. |
Accessing nested object properties safely and concisely. |
Nullish Coalescing Operator |
A syntax for providing a default value when a variable is null or undefined, simplifying code and reducing errors. |
const value = input ?? defaultValue; |
Implement a script that uses the nullish coalescing operator to provide default values when variables are null or undefined, simplifying code and reducing errors. |
Providing default values for null or undefined variables. |
for...of Loop |
A loop that iterates over iterable objects (like arrays, strings, and generators), allowing you to work with their elements directly. |
for (const element of iterable) { /*...*/ } |
Create a script that uses the for...of loop to iterate over iterable objects and work with their elements directly. |
Iterating over iterable objects. |
Object.entries() |
A method that returns an array of a given object's own enumerable property [key, value] pairs, allowing you to work with objects as arrays of key-value pairs. |
const entries = Object.entries(obj); |
Implement a script that uses Object.entries() to convert an object into an array of key-value pairs, enabling easier manipulation and iteration. |
Working with objects as arrays of key-value pairs. |
Object.values() |
A method that returns an array of a given object's own enumerable property values, allowing you to work with objects as arrays of values. |
const values = Object.values(obj); |
Create a script that uses Object.values() to convert an object into an array of values, enabling easier manipulation and iteration. |
Working with objects as arrays of values. |
Array.flat() |
A method that creates a new array with all sub-array elements concatenated into it recursively up to the specified depth, allowing you to flatten nested arrays. |
const flattened = arr.flat(depth); |
Implement a script that uses Array.flat() to flatten nested arrays, simplifying array manipulation and iteration. |
Flattening nested arrays. |
Array.flatMap() |
A method that first maps each element using a mapping function, then flattens the result into a new array, allowing you to map and flatten arrays in a single operation. |
const flatMapped = arr.flatMap(callback); |
Create a script that uses Array.flatMap() to map and flatten arrays in a single operation, simplifying array manipulation and iteration. |
Mapping and flattening arrays in a single operation. |
Intersection Observer API |
An API for efficiently detecting when elements become visible or intersect with other elements, allowing you to create performant lazy-loading, infinite scrolling, and other effects. |
const observer = new IntersectionObserver(callback, options); |
Implement a script that uses the Intersection Observer API to detect when elements become visible or intersect with other elements, enabling performant lazy-loading, infinite scrolling, and other effects. |
Detecting element visibility and intersection. |