JavaScript Snippets
Useful JavaScript code snippets for common programming tasks
Array Map
javascriptTransform array elements using map function
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);String Template
javascriptUse template literals for string interpolation
const name = 'World';
const greeting = `Hello, ${name}!`;Array Methods
javascriptCommon array methods in JavaScript
const numbers = [1, 2, 3, 4, 5];
// Filter even numbers
const evens = numbers.filter(n => n % 2 === 0);
// Reduce to sum
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
// Find first number > 3
const found = numbers.find(n => n > 3);Async/Await
javascriptHandle asynchronous operations
async function fetchUserData() {
try {
const response = await fetch('https://api.example.com/user');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}