JavaScript ES6 Features
ES6 (2015) and later versions added features that make JavaScript shorter and easier to read. These are the ones you will use every day.
Destructuring arrays
const colors = ["red", "green", "blue"];
const [first, second] = colors;
console.log(first, second);
Output of the above program is
red green
Destructuring objects
const user = { name: "Robin", age: 25, city: "Delhi" };
const { name, age } = user;
console.log(name, age);
const { city: town = "Unknown" } = user; // rename
console.log(town);
Output of the above program is
Robin 25
Delhi
You can also destructure in function parameters: function show({ name, age }) { ... }.
Spread operator (…)
const a = [1, 2];
const b = [...a, 3, 4];
console.log(b);
const defaults = { theme: "light", size: 14 };
const settings = { ...defaults, size: 18 };
console.log(settings);
console.log(Math.max(...[3, 9, 5]));
Output of the above program is
[ 1, 2, 3, 4 ]
{ theme: "light", size: 18 }
9
Rest parameters
function sum(first, ...others) {
return first + others.length;
}
console.log(sum(10, "a", "b", "c"));
Output of the above program is
13
Other useful features
- Template literals:
`Hello ${name}`, see Strings. - Arrow functions: see Arrow Functions.
- Default parameters:
function f(x = 10). - Optional chaining and nullish:
user?.address?.city ?? "none". - Shorthand properties:
{ name, age }instead of{ name: name, age: age }. - Modules:
importandexport, see Modules.
const city = undefined;
console.log(city ?? "none");
const x = 5, y = 6;
console.log({ x, y });
Output of the above program is
none
{ x: 5, y: 6 }
Summary
- Destructuring pulls values out of arrays and objects.
- Spread
...copies and merges, rest...collects. - Learn the others as you meet them in code.
- Next: JavaScript JSON.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |