Destructuring in Javascript

In JavaScript, destructuring is a feature that allows you to extract data from arrays or objects and assign them to variables. It is a shorthand way of creating multiple variables from an array or object's properties.

Here is an example of destructuring an array:

let numbers = [1, 2, 3, 4, 5];

let [one, two, three, four, five] = numbers;

console.log(one); // 1

console.log(two); // 2

console.log(three); // 3

console.log(four); // 4

console.log(five); // 5

In this above example, the variables one, two, three, four, and five are assigned the corresponding values from the numbers array.

Here is an example of destructuring an object:

let person = {

  name: "John Doe",

  age: 30,

  address: {

    street: "123 Main St",

    city: "Anytown",

    state: "Anystate",

    zip: "12345"

  }

};

let {name, age, address} = person;

console.log(name); // "John Doe"

console.log(age); // 30

console.log(address); // { street: "123 Main St", city: "Anytown", state: "Anystate", zip: "12345" }


In this above example, the variables name, age, and address are assigned the corresponding values from the person object.

You can also use destructuring to assign new variable names to the properties being destructured, like so:

let {name: fullName, age: ageOfPerson, address: fullAddress } = person;

console.log(fullName); // "John Doe"

console.log(ageOfPerson); // 30

console.log(fullAddress); // { street: "123 Main St", city: "Anytown", state: "Anystate", zip: "12345" }

 

Also, you can use destructuring to access nested properties, like so:

let {address: { city, state, zip } } = person;

console.log(city); // "Anytown"

console.log(state); // "Anystate"

console.log(zip); // "12345"

 

Destructuring can also be used to extract data from function arguments:

function getPerson({ name, age }) {

  console.log(name);

  console.log(age);

}

getPerson(person); // "John Doe", 30


Rest Property

The Rest properly which is indicated by ...rest notation is a very unique and useful way to quickly assign remaining properties of the array or object to a completely new object or array.

For example:

const { one, ...numbers} = {a:10, b:20, c:30}

console.log(...numbers}//b:20, c:30

Destructuring is a convenient and powerful feature of JavaScript that can help you write more concise and readable code.

Post a Comment

0 Comments