Destructuring is an ES6 feature in JavaScript. It allows us to extract values from arrays or objects and store them in separate variables easily.
Destructuring means taking values from an array or object and assigning them to variables.
There are two main types:
Array Destructuring:
Array destructuring uses square brackets [].
Without destructuring:
let fruits = ["Apple", "Mango", "Orange"];
let a = fruits[0];
let b = fruits[1];
let c = fruits[2];
console.log(a);
console.log(b);
console.log(c);
With destructuring:
let fruits = ["Apple", "Mango", "Orange"];
let [a, b, c] = fruits;
console.log(a);
console.log(b);
console.log(c);
Output:
Apple
Mango
Orange
Object Destructuring:
Object destructuring uses curly brackets {}.
Without destructuring:
let student = {
name: "Sathish",
age: 23,
city: "Chennai"
};
let name = student.name;
let age = student.age;
console.log(name);
console.log(age);
With destructuring:
let student = {
name: "Sathish",
age: 23,
city: "Chennai"
};
let { name, age, city } = student;
console.log(name);
console.log(age);
console.log(city);
Output:
Sathish
23
Chennai