Taking it all apart — JS

Destructuring in JS

Photo by Gabriel Heinzer on Unsplash

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:

Output received

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:

Output received

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:

Output received

Thus concludes the tale of destructuring in JS.

Follow me on my socials:

Github

Linkedin

Twitter

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mohajit Paul

Upcoming SDE | Blockchain and Front End Developer | Meta and Web3.0 Enthusiast | https://linktr.ee/mohajit