JavaScript stellt eine umfangreiche Sammlung von eingebauten Funktionen und Methoden zur Verfügung, die als Grundbausteine für die Entwicklung dienen. Diese Funktionen sind Teil der Sprache selbst und können ohne zusätzliche Importe oder Bibliotheken verwendet werden. Ein fundiertes Verständnis dieser Built-ins ist essentiell für effiziente JavaScript-Entwicklung.
Die globalen Funktionen sind direkt im globalen Scope verfügbar und können überall im Code aufgerufen werden, ohne dass ein Objekt-Kontext erforderlich ist.
// Zahlen-Parsing
const intValue = parseInt("123", 10); // 123
const floatValue = parseFloat("123.45"); // 123.45
const invalidParse = parseInt("abc"); // NaN
// Typ-Prüfungen
const checkNaN = isNaN("hello"); // true
const checkFinite = isFinite(100); // true
const checkInteger = Number.isInteger(42); // trueDie parseInt()-Funktion sollte immer mit einer
expliziten Basis verwendet werden, um unerwartete Ergebnisse zu
vermeiden. Die moderneren Number-Methoden bieten präzisere
Typ-Prüfungen als die globalen Varianten.
// URL-Kodierung
const encoded = encodeURIComponent("Hello World!");
// "Hello%20World!"
const decoded = decodeURIComponent(encoded);
// "Hello World!"
// Vollständige URI-Kodierung
const fullURI = encodeURI("https://example.com/search?q=hello world");Strings verfügen über eine Vielzahl von Methoden für Manipulation, Suche und Formatierung. Moderne String-Methoden arbeiten Unicode-bewusst und sind performant optimiert.
const text = "JavaScript ist eine vielseitige Sprache";
// Positionsbasierte Suche
const index = text.indexOf("Script"); // 4
const lastIndex = text.lastIndexOf("e"); // 37
const includes = text.includes("Java"); // true
// Moderne Suchmethoden
const startsWith = text.startsWith("Java"); // true
const endsWith = text.endsWith("Sprache"); // true
// Extraktion
const substring = text.substring(0, 10); // "JavaScript"
const slice = text.slice(-7); // "Sprache"const rawText = " JavaScript Entwicklung ";
// Bereinigung
const trimmed = rawText.trim(); // "JavaScript Entwicklung"
const upper = trimmed.toUpperCase(); // "JAVASCRIPT ENTWICKLUNG"
const lower = trimmed.toLowerCase(); // "javascript entwicklung"
// Ersetzung
const replaced = trimmed.replace("JavaScript", "JS");
const globalReplace = text.replace(/e/g, "3"); // Regex für globale Ersetzung
// Aufteilung
const words = trimmed.split(" "); // ["JavaScript", "Entwicklung"]Arrays bieten umfangreiche Methoden für funktionale Programmierung, die das Fundament für moderne JavaScript-Entwicklung bilden. Die Methoden lassen sich in mutierende und nicht-mutierende Kategorien unterteilen.
const numbers = [1, 2, 3, 4, 5];
// Transformation
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
const filtered = numbers.filter(n => n > 3); // [4, 5]
const reduced = numbers.reduce((sum, n) => sum + n, 0); // 15
// Prüfungen
const hasEven = numbers.some(n => n % 2 === 0); // true
const allPositive = numbers.every(n => n > 0); // true
// Suche
const found = numbers.find(n => n > 3); // 4
const foundIndex = numbers.findIndex(n => n > 3); // 3const mutableArray = [1, 2, 3];
// Hinzufügen/Entfernen
mutableArray.push(4); // [1, 2, 3, 4]
mutableArray.unshift(0); // [0, 1, 2, 3, 4]
const popped = mutableArray.pop(); // 4, Array: [0, 1, 2, 3]
const shifted = mutableArray.shift(); // 0, Array: [1, 2, 3]
// Splice für komplexe Operationen
mutableArray.splice(1, 1, 'inserted'); // [1, 'inserted', 3]Die statischen Methoden des Object-Konstruktors sind
fundamental für die Arbeit mit Objekten und deren Metadaten.
const user = {
name: "Alice",
age: 30,
email: "alice@example.com"
};
// Schlüssel und Werte extrahieren
const keys = Object.keys(user); // ["name", "age", "email"]
const values = Object.values(user); // ["Alice", 30, "alice@example.com"]
const entries = Object.entries(user); // [["name", "Alice"], ...]
// Objekt-Komposition
const defaults = { theme: "dark", language: "en" };
const config = Object.assign({}, defaults, { theme: "light" });
// Moderne Alternative
const modernConfig = { ...defaults, theme: "light" };
// Property-Kontrolle
const hasName = Object.hasOwnProperty.call(user, 'name'); // true
const descriptor = Object.getOwnPropertyDescriptor(user, 'name');Das Math-Objekt stellt mathematische Konstanten und
Funktionen zur Verfügung, die für numerische Berechnungen unerlässlich
sind.
// Konstanten
const pi = Math.PI; // 3.141592653589793
const euler = Math.E; // 2.718281828459045
// Rundungsfunktionen
const rounded = Math.round(4.7); // 5
const ceiling = Math.ceil(4.1); // 5
const floor = Math.floor(4.9); // 4
const truncated = Math.trunc(-4.9); // -4
// Extremwerte
const maximum = Math.max(1, 3, 2); // 3
const minimum = Math.min(1, 3, 2); // 1
// Zufallszahlen
const random = Math.random(); // 0 <= x < 1
const randomInt = Math.floor(Math.random() * 10); // 0-9
// Exponential- und Logarithmusfunktionen
const power = Math.pow(2, 3); // 8
const squareRoot = Math.sqrt(16); // 4
const naturalLog = Math.log(Math.E); // 1Das Date-Objekt ermöglicht die Arbeit mit Datums- und
Zeitwerten. Moderne Anwendungen sollten jedoch für komplexe
Datums-Operationen spezialisierte Bibliotheken in Betracht ziehen.
// Erstellung
const now = new Date();
const specific = new Date('2024-03-15T10:30:00Z');
const fromTimestamp = new Date(1710505800000);
// Formatierung
const isoString = now.toISOString(); // "2024-03-15T10:30:00.000Z"
const localeString = now.toLocaleString('de-DE');
const dateOnly = now.toDateString();
// Komponenten-Zugriff
const year = now.getFullYear();
const month = now.getMonth(); // 0-basiert!
const day = now.getDate();
const hours = now.getHours();
// Zeitstempel
const timestamp = now.getTime(); // Millisekunden seit 1970
const dateNow = Date.now(); // Statische AlternativeJSON (JavaScript Object Notation) ist das Standardformat für Datenaustausch in modernen Webanwendungen.
const data = {
id: 1,
name: "Alice",
active: true,
skills: ["JavaScript", "React", "Node.js"]
};
// Serialisierung
const jsonString = JSON.stringify(data);
const prettyJson = JSON.stringify(data, null, 2); // Formatiert
// Benutzerdefinierte Serialisierung
const customJson = JSON.stringify(data, (key, value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
});
// Deserialisierung
const parsed = JSON.parse(jsonString);
// Sichere Deserialisierung mit Error-Handling
try {
const safeParsed = JSON.parse(potentiallyInvalidJson);
} catch (error) {
console.error('JSON parsing failed:', error.message);
}Die console-API bietet vielfältige Debugging- und
Logging-Möglichkeiten, die über das einfache console.log()
hinausgehen.
// Basis-Logging
console.log("Information");
console.warn("Warnung");
console.error("Fehler");
console.info("Info");
// Strukturierte Ausgabe
const user = { name: "Alice", age: 30 };
console.table(user); // Tabellarische Darstellung
console.dir(user, { depth: null }); // Vollständige Objektstruktur
// Gruppierung
console.group("User Processing");
console.log("Validating user data");
console.log("Saving to database");
console.groupEnd();
// Performance-Messung
console.time("operation");
// Zeitaufwändige Operation
console.timeEnd("operation"); // Gibt Dauer aus
// Bedingte Ausgabe
console.assert(user.age > 0, "Age must be positive");Viele eingebaute Funktionen können Fehler auslösen, die angemessen behandelt werden müssen.
// Sichere Verwendung von JSON.parse
function safeJsonParse(jsonString, defaultValue = null) {
try {
return JSON.parse(jsonString);
} catch (error) {
console.warn('JSON parsing failed:', error.message);
return defaultValue;
}
}
// Validierung vor parseInt
function safeParseInt(value, radix = 10) {
if (typeof value !== 'string' && typeof value !== 'number') {
return NaN;
}
const result = parseInt(value, radix);
return isNaN(result) ? 0 : result;
}
// Defensive Array-Operationen
function safeArrayOperation(arr, operation) {
if (!Array.isArray(arr)) {
throw new TypeError('Expected an array');
}
return operation(arr);
}Die Wahl der richtigen eingebauten Funktion kann erhebliche Auswirkungen auf die Performance haben.
// Ineffizient für große Arrays
const found = largeArray.filter(item => item.id === targetId)[0];
// Effizienter
const found = largeArray.find(item => item.id === targetId);
// String-Concatenation vs. Template Literals
// Für wenige Strings: Template Literals
const message = `Hello ${name}, you have ${count} messages`;
// Für viele Strings: Array.join()
const parts = ['Hello', name, 'you have', count, 'messages'];
const message = parts.join(' ');Die effektive Nutzung eingebauter Funktionen folgt bewährten Mustern:
find() statt filter()[0] für einzelne
ElementeDie Beherrschung dieser eingebauten Funktionen bildet das Fundament für die fortgeschrittenen Konzepte, die in den Kapiteln über funktionale Programmierung und asynchrones JavaScript behandelt werden.