JS: Destructuring and Spread operator

satya - 12/13/2024, 9:58:20 PM

Two concepts

  1. Destructring or unpacking objects or arrays
  2. Spread operator

satya - 12/13/2024, 9:58:54 PM

Start with declaring arrays and objects


// Arrays
const fruits = ["apple", "banana", "cherry"];
const emptyArray = [];
const mixed = [42, "hello", true];
const numbers = [1, 2, 3, 4, 5];
const newArray = Array(3);

// Objects
const person = { name: "Alice", age: 25 };
const emptyObject = {};
const user = { name: "Bob", address: { city: "New York", zip: "10001" } };
const bike = { brand: "Yamaha", color: "red" };

satya - 12/13/2024, 9:59:44 PM

Lets unpack some of those arrays and objects into variables on the left


// Destructuring Arrays
const numbers = [1, 2, 3, 4];
const [first, second, third] = numbers;
const [x, , y] = numbers;
const [a, b = 0, c, d = 10] = numbers;

// Destructuring Objects
const person = { name: "Alice", age: 25, city: "New York" };
const { name, age } = person;
const { city: location } = person;
const { name: fullName, country = "USA" } = person;

// Combining Array and Object Destructuring
const people = [{ name: "Bob", age: 30 }, { name: "Carol", age: 35 }];
const [{ name: firstName }, { age: secondPersonAge }] = people;

satya - 12/13/2024, 10:01:50 PM

Notice how the operators work on the left hand side


//Get the first element from the array of numbers
const [first] = numbers;

//Get name and age from the person objects
const { name, age } = person;

satya - 12/13/2024, 10:03:11 PM

Note

  1. Notice the meaning of [] and {} changes when they are on the left side
  2. They are not creating arrays or objects, as they do if on the right
  3. Instead they are creating variables....

satya - 1/8/2025, 3:56:24 PM

Consider this


const { city: location } = person;

satya - 1/8/2025, 3:58:39 PM

This means

  1. Extract the property "city" from person object and assign it to the constant "locaton"
  2. ...
  3. input: city
  4. output: location
  5. ...
  6. location = person.city