Mastering these ES6 features will make your code cleaner, shorter, and more powerful. Let’s break them down:
1️⃣ Arrow Functions
Arrow functions are a shorter way to write function expressions.
🔹 Syntax:
const add = (a, b) => a + b;
🔹 Key Points:
• No need for function keyword
• If one expression, return is implicit
• this is not rebound — it uses the parent scope’s
this 🧪 Example:
// Regular function
function greet(name) {
return "Hello, " + name;
}
// Arrow version
const greet = name => Hello, ${name};
console.log(greet("Riya")); // Hello, Riya
2️⃣ Destructuring
Destructuring lets you extract values from arrays or objects into variables.
🔹 Object Destructuring:
const user = { name: "Aman", age: 25 };
const { name, age } = user;
console.log(name); // Aman
🔹 **Array Destructuring:** javascript
const numbers = [10, 20, 30];
const [a, b] = numbers;
console.log(a); // 10
🧠 **Real Use:** javascript
function displayUser({ name, age }) {
console.log(${name} is ${age} years old.);
}
displayUser({ name: "Tara", age: 22 });3️⃣ Spread & Rest Operators (...)
✅ Spread – Expands elements from an array or object
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4];
console.log(arr2); // [1, 2, 3, 4]
🔹 **Copying objects:** javascript
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }
✅ Rest – Collects remaining elements into an array
🔹 In function parameters:
function sum(...nums) {
return nums.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3)); // 6
🔹 **In destructuring:** javascript
const [first, ...rest] = [10, 20, 30];
console.log(rest); // [20, 30]🎯 Practice Tips:
• Convert a function to an arrow function
• Use destructuring in function arguments
• Merge arrays or objects using spread
• Write a function using rest to handle any number of inputs
💬 Tap ❤️ for more!