🚀 Modern JavaScript Code Examples (ES6+)
With ES6 and beyond, JavaScript has become more expressive, cleaner, and more powerful. Below are modern examples to replace older patterns using concise ES6+ features.
✅ Arrow Functions
// Old
function double(x) {
return x * 2;
}
// Modern
const double = x => x * 2;
✅ Template Literals
// Old
var name = "Sara";
console.log("Hello " + name);
// Modern
const name = "Sara";
console.log(`Hello ${name}`);
✅ Destructuring
// Old
const user = { name: "Tom", age: 30 };
const name = user.name;
// Modern
const { name, age } = user;
✅ Spread Operator
const oldArray = [1, 2, 3];
const newArray = [...oldArray, 4, 5];
✅ Array Methods
const numbers = [1, 2, 3, 4];
// Map
const doubled = numbers.map(n => n * 2);
// Filter
const evens = numbers.filter(n => n % 2 === 0);
✅ Optional Chaining
const user = { profile: { email: "me@example.com" } };
// Old
if (user && user.profile && user.profile.email) {
console.log(user.profile.email);
}
// Modern
console.log(user?.profile?.email);
✅ Nullish Coalescing
const username = null;
const nameToDisplay = username ?? "Guest";
✅ Promises and Async/Await
// Promise
fetch('https://api.example.com/data')
.then(res => res.json())
.then(data => console.log(data));
// Async/Await
async function getData() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
console.log(data);
}
getData();
🧠 Practice Tip: Try converting your old functions and logic to these modern forms to improve readability and maintainability.