Introduction
Modern JavaScript has evolved significantly with the introduction of ES6+ features. The MDN Web Docs provide comprehensive documentation of these features.
ES6+ Features
Arrow Functions
// Traditional Function
function add(a, b) {
return a + b;
}
// Arrow Function
const add = (a, b) => a + b;
// Arrow Function with Context Binding
const obj = {
value: 42,
getValue: () => this.value, // Lexical this
getValueTraditional: function() {
return this.value; // Dynamic this
}
};
Destructuring and Spread Operator
// Object Destructuring
const user = {
name: 'John',
age: 30,
address: {
city: 'New York',
country: 'USA'
}
};
const { name, age, address: { city } } = user;
// Array Destructuring
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
// Spread Operator
const newArray = [...numbers, 6, 7];
const newObject = { ...user, email: 'john@example.com' };
Template Literals
const name = 'World';
const greeting = `Hello ${name}!`;
// Tagged Templates
function highlight(strings, ...values) {
return strings.reduce((result, str, i) =>
`${result}${str}${values[i] ? `${values[i]}` : ''}`,
'');
}
const keyword = 'JavaScript';
const text = highlight`Learn ${keyword} today!`;
Async Programming
Modern JavaScript provides powerful tools for handling asynchronous operations. Learn more from the MDN Promise Guide.
Promises and Async/Await
// Promise Example
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = { id: 1, name: 'Example' };
Math.random() > 0.5 ? resolve(data) : reject('Error fetching data');
}, 1000);
});
};
// Using Promise Chain
fetchData()
.then(data => console.log(data))
.catch(error => console.error(error));
// Using Async/Await
async function getData() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error(error);
}
}
// Promise.all Example
async function fetchMultipleData() {
try {
const results = await Promise.all([
fetch('/api/users'),
fetch('/api/posts'),
fetch('/api/comments')
]);
const data = await Promise.all(results.map(r => r.json()));
return data;
} catch (error) {
console.error('Error fetching data:', error);
}
}
Modules and Import/Export
JavaScript modules help organize code into reusable components. Check the MDN Modules Guide for detailed information.
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export default class Calculator {
multiply(a, b) {
return a * b;
}
}
// main.js
import Calculator, { add, subtract } from './math.js';
import * as mathUtils from './math.js';
const calc = new Calculator();
console.log(add(5, 3)); // 8
console.log(subtract(10, 4)); // 6
console.log(calc.multiply(2, 6)); // 12
Modern Data Structures
Map and Set
// Map Example
const userMap = new Map();
userMap.set('john', { name: 'John', age: 30 });
userMap.set('jane', { name: 'Jane', age: 25 });
// Set Example
const uniqueNumbers = new Set([1, 2, 2, 3, 3, 4]);
console.log([...uniqueNumbers]); // [1, 2, 3, 4]
// WeakMap and WeakRef
const cache = new WeakMap();
let obj = { data: 'valuable' };
cache.set(obj, 'metadata');
// When obj is garbage collected, its entry in cache is automatically removed
Best Practices
Use Strict Mode
'use strict';
// This will throw an error in strict mode
function example() {
undeclaredVariable = 42; // ReferenceError
}
Error Handling
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
}
}
async function validateUser(user) {
try {
if (!user.name) {
throw new ValidationError('Name is required');
}
// More validation...
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation failed:', error.message);
} else {
console.error('Unexpected error:', error);
throw error; // Re-throw unexpected errors
}
}
}
Performance Optimization
// Use Object/Array Destructuring
const { id, name } = user;
// Use Array Methods Instead of Loops
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
// Debounce Function
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}