50 phút
Các tính năng mới trong ES6+
Destructuring
// Array destructuring
let numbers = [1, 2, 3];
let [first, second, third] = numbers;
console.log(first, second, third); // 1 2 3
// Object destructuring
let person = { name: "John", age: 30, city: "New York" };
let { name, age } = person;
console.log(name, age); // John 30
// Destructuring trong tham số hàm
function printPerson({ name, age }) {
console.log(`${name} is ${age} years old`);
}
Spread và Rest Operators
// Spread với mảng
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]
// Spread với object
let obj1 = { a: 1, b: 2 };
let obj2 = { c: 3, d: 4 };
let merged = { ...obj1, ...obj2 };
console.log(merged); // { a: 1, b: 2, c: 3, d: 4 }
// Rest parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15
Template Literals
let name = "John";
let age = 30;
// String interpolation
let message = `Hello, my name is ${name} and I'm ${age} years old.`;
console.log(message);
// Multi-line strings
let multiLine = `
This is a
multi-line
string
`;
Default Parameters
function greet(name = "Guest", greeting = "Hello") {
console.log(`${greeting}, ${name}!`);
}
greet(); // "Hello, Guest!"
greet("John"); // "Hello, John!"
greet("Jane", "Hi"); // "Hi, Jane!"
Optional Chaining và Nullish Coalescing
let user = {
profile: {
name: "John",
address: {
city: "New York"
}
}
};
// Optional chaining
let city = user?.profile?.address?.city;
console.log(city); // "New York"
let invalidCity = user?.profile?.invalid?.city;
console.log(invalidCity); // undefined
// Nullish coalescing
let defaultValue = user?.invalidProp ?? "Default Value";
console.log(defaultValue); // "Default Value"