JavaScript(JS) Destructuring Assignment

w‮gi.ww‬iftidea.com

JavaScript Destructuring Assignment is a way to extract values from objects or arrays into separate variables. It is a shorthand syntax for assigning values to variables from an object or array.

Here are some examples of using destructuring assignment in JavaScript:

  1. Destructuring an object:
const person = { name: "John", age: 30 };

const { name, age } = person;

console.log(name); // output: "John"
console.log(age); // output: 30

In this example, we define an object person with two properties name and age. We then use destructuring assignment to assign the values of name and age to separate variables with the same names.

  1. Destructuring an array:
const numbers = [1, 2, 3];

const [a, b, c] = numbers;

console.log(a); // output: 1
console.log(b); // output: 2
console.log(c); // output: 3

In this example, we define an array numbers with three values. We then use destructuring assignment to assign the values of the array to separate variables a, b, and c.

  1. Assigning default values:
const person = { name: "John" };

const { name, age = 30 } = person;

console.log(name); // output: "John"
console.log(age); // output: 30

In this example, we define an object person with one property name. We then use destructuring assignment to assign the value of name to a variable name, and the value of age to a variable with a default value of 30.