Mastering modern JavaScript is key to writing cleaner, faster, and more efficient code. Here's a breakdown of essential ES6+ features with examples.
1๏ธโฃ let const (Block Scope)
let and const replace var.
โข let = reassignable
โข const = constant (can't reassign)
let score = 90;
const name = "Alice";
โถ๏ธ Use
const by default. Switch to let if the value changes.2๏ธโฃ Arrow Functions (=>)
Shorter syntax for functions.
const add = (a, b) => a + b;
โถ๏ธ No
this binding โ useful in callbacks.3๏ธโฃ Template Literals
Use backticks (
`) for multiline strings and variable interpolation. const user = "John";
console.log(Hello, ${user}!);
4๏ธโฃ Destructuring
Extract values from objects or arrays.
const person = { name: "Sam", age: 30 };
const { name, age } = person;
5๏ธโฃ Spread and Rest Operators (...)
โข Spread โ expand arrays/objects
โข Rest โ collect arguments
const nums = [1, 2, 3];
const newNums = [...nums, 4];
function sum(...args) {
return args.reduce((a, b) => a + b);
}
6๏ธโฃ Default Parameters
function greet(name = "Guest") {
return Hello, ${name}!;
}
7๏ธโฃ for...of Loop
Loop over iterable items like arrays.
for (let fruit of ["apple", "banana"]) {
console.log(fruit);
}
8๏ธโฃ Promises (Basics)
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Done"), 1000);
});
};
Mini Practice Task:
โ Convert a regular function to arrow syntax
โ Use destructuring to get properties from an object
โ Create a promise that resolves after 2 seconds
๐ฌ Tap โค๏ธ for more!