INSTACK 360

ES6+ Features: Destructuring, Spread, and Rest

Write cleaner, more modern JS. Master object/array destructuring and the highly versatile spread and rest operators.

Advanced 5 min read

Destructuring Assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Object Destructuring

const user = { name: "John", age: 30, city: "NY" };
const { name, age } = user;

console.log(name); // John

Array Destructuring

const rgb = [255, 200, 0];
const [red, green, blue] = rgb;

The Spread Operator (...)

The spread operator allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.

const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]

const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }

The Rest Parameter (...)

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array.

function sum(...args) {
  return args.reduce((total, num) => total + num, 0);
}