2024-09-08
Explore modern JavaScript features from ES6 and beyond that make your code cleaner, more efficient, and more maintainable.
JavaScript has evolved dramatically since ES6 (ES2015). This guide covers the most important modern features that every JavaScript developer should master, from arrow functions to async/await and beyond.
// Arrow functions preserve 'this' context
class Timer {
constructor() {
this.seconds = 0;
// Traditional function loses 'this'
setInterval(function() {
// this.seconds++; // Error: 'this' is undefined
}, 1000);
// Arrow function preserves 'this'
setInterval(() => {
this.seconds++; // Works correctly
}, 1000);
}
}
// Extract properties from objects
const user = { name: 'Alice', age: 30, email: 'alice@example.com' };
const { name, age } = user;
// With renaming and defaults
const { name: userName, role = 'user' } = user;
// In function parameters
function greet({ name, age }) {
return `Hello ${name}, you are ${age} years old`;
}
// Array spreading
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
// Object spreading
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
// Function arguments
const nums = [1, 2, 3];
Math.max(...nums); // 3
Clean asynchronous code with async/await:
// Traditional promise chaining
fetch('/api/user')
.then(response => response.json())
.then(user => fetch(`/api/posts/${user.id}`))
.then(response => response.json())
.then(posts => console.log(posts))
.catch(error => console.error(error));
// With async/await
async function getUserPosts() {
try {
const userResponse = await fetch('/api/user');
const user = await userResponse.json();
const postsResponse = await fetch(`/api/posts/${user.id}`);
const posts = await postsResponse.json();
console.log(posts);
} catch (error) {
console.error(error);
}
}
// Basic interpolation
const name = 'World';
const greeting = `Hello, ${name}!`;
// Multi-line strings
const html = `
<div>
<h1>${title}</h1>
<p>${content}</p>
</div>
`;
// Tagged templates
function sql(strings, ...values) {
// Safely escape SQL values
return strings.reduce((result, str, i) =>
result + str + (values[i] ? escape(values[i]) : ''), '');
}
const query = sql`SELECT * FROM users WHERE id = ${userId}`;
// Optional chaining (?.)
const user = { profile: { address: { city: 'New York' } } };
// Safe property access
const city = user?.profile?.address?.city; // 'New York'
const country = user?.profile?.address?.country; // undefined
// Nullish coalescing (??)
const port = process.env.PORT ?? 3000;
const username = user.name ?? 'Anonymous';
// Combining both
const displayName = user?.profile?.name ?? 'Guest User';
Published on 2024-09-08 • Category: Programming
← Back to BlogFree online developer tools and utilities for encoding, formatting, generating, and analyzing data. No registration required - all tools work directly in your browser.
Built for developers, by developers. Privacy-focused and open source.
Free online tools for Base64 encoding, JSON formatting, URL encoding, hash generation, UUID creation, QR codes, JWT decoding, timestamp conversion, regex testing, and more.
© 2024 NarvikHub. All rights reserved.