Taking it all apart — JS
Destructuring in JS
With destructuring, we can “unpack” an object and assign its properties to new variables. For example, let’s look at object destructuring:
We can look at Destructuring as trying to make a tasty egg sandwich. We only take out those components from the refrigerator that we need for the sandwich i.e Bread, Bologna, egg, etc. We wouldn't take out all the items we have in the fridge right? That is the same case as Destruct element in JS.
Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and store it in separate variables. Destructuring allows us to extract numerous attributes or objects at once from an array.
Let us look at the syntax:
const obj = {
a: 2,
b: 3,
}
// destructure assignment
const { a, b } = obj;
console.log(a); // 2
console.log(b); // 3
Here,
const { a,b } = obj;
a directly maps to the first element of obj, while b does the same for the second element in obj.
Types of Destructuring:
Assignment to existing variable names:
var student = { // Object we will be destructuring
firstname: 'Mohajit',
lastname: 'Paul',
dateofbirth: '2002'
};
// Destructuring:
const { firstname, lastname, dateofbirth } = student;
console.log( firstname, lastname, dateofbirth);
Output:
2. Assignment to new variable names:
Input:
var student = { // Object to destructure
firstname: 'Mohajit',
lastname: 'Paul',
dateofbirth: '2002'
};
// Destructuring obj with different names:
const { firstname: F1N, lastname: L1N, dateofbirth: dob } = student;
console.log( F1N, L1N , dob);
Output:
3. Assignment with default values:
Input:
var student = { // Object to destructure
firstname: 'Mohajit',
lastname: 'Paul',
dateofbirth: '2002'
};
// Destructuring - variables without
// assigning default values
var { firstname, lastname, country } = student;
console.log("Without setting default values")
console.log( firstname, lastname, grade);
// Destructuring - variables by
// assigning default values
var { firstname = 'default firstname',
lastname = 'default lastname',
grade = 'default grade' } = student;
console.log("\n After setting default values")
console.log( firstname, lastname, grade);
Output:
Thus concludes the tale of destructuring in JS.
Follow me on my socials: