JavaScriptadvanced 9 min
Destructuring, spread, template strings, default parameters, optional chaining and more.
The modern syntax you will see in almost every JavaScript project: template strings, destructuring, spread and rest, default parameters, optional chaining and nullish coalescing.
These features, introduced from 2015 onwards (ES6 and later), make code shorter and safer. Tutorials, libraries and teammates all use them, so you need to read them fluently.
${} to insert values: `Hello ${name}`. They can span several lines.const { name, age } = user; and const [first, second] = list;....) expands an array or object: [...a, ...b] joins arrays; { ...obj, extra: 1 } copies an object with a change.function sum(...nums) { ... }.function greet(name = "friend").user?.address?.city returns undefined instead of throwing when something in the chain is missing.value ?? "default" uses the default only when the value is null or undefined (unlike ||, which also replaces 0 and "").(a, b) => a + b are short function expressions.export and import split code across files.name and age out of the object. The template string prints Asha is 30.first is "a", and others holds the remaining three items.sum(...nums) collects any number of arguments into an array and adds them: 10."friend" when no argument is given.user with a new age. The original is untouched: 31 30.user.job?.title is undefined rather than an error, because job does not exist.0 || 10 is 10 (zero counts as false) but 0 ?? 10 is 0 (zero is a real value).Destructure city from user.address in one line, and give it a default of "Unknown".
|| for defaults when 0 or an empty string are valid values. Use ??.null or undefined, which throws an error.?. avoids errors on missing data; ?? gives safe defaults.Next: handling errors gracefully.
const user = { name: "Asha", age: 30, address: { city: "Pune" } };
const { name, age } = user;
console.log(`${name} is ${age}`);
const [first, ...others] = ["a", "b", "c", "d"];
console.log(first, others);
function sum(...nums) {
return nums.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4));
function greet(who = "friend") {
return `Hello, ${who}!`;
}
console.log(greet(), greet("Ravi"));
const updated = { ...user, age: 31 };
console.log(updated.age, user.age);
console.log(user.address?.city);
console.log(user.job?.title);
console.log(0 || 10, 0 ?? 10);