Destructuring lets you extract values from arrays or objects into variables.
const person = { name: "Alice", age: 25 };
const { name, age } = person;
console.log(name); // Alice
Use backticks (`) to embed expressions using ${...}.
const name = "Bob";
const greeting = `Hello, ${name}!`;
console.log(greeting); // Hello, Bob!
Spread (...) expands arrays or objects.
Rest (...) collects multiple elements into one.
// Spread
const arr1 = [1, 2];
const arr2 = [...arr1, 3]; // [1, 2, 3]
// Rest
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6
let and const are block-scoped. Use const for constants.
let count = 10;
const name = "Charlie";
Arrow functions are shorter and don't bind their own this.
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
Set default values in function parameters to avoid undefined.
function greet(name = "Guest") {
console.log(`Hello, ${name}`);
}
greet(); // Hello, Guest
Create objects using shorthand syntax when key and variable name match.
const name = "David";
const user = {
name,
greet() {
console.log(`Hi ${this.name}`);
}
};
user.greet(); // Hi David
?.)Access deep properties safely without throwing errors.
const user = { profile: null };
console.log(user.profile?.name); // undefined, no error
??)
Return right-hand side only if left is null or undefined.
const username = null;
const defaultName = username ?? "Anonymous";
console.log(defaultName); // Anonymous