JavaScript(JS) Destructuring Assignment
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:
- 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.
- 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
.
- 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
.