Skip to main content

Command Palette

Search for a command to run...

Destructuring in JavaScript

Updated
β€’5 min read

What are we gonna study?

Today in this blog, we'll be doing PHD on Destructuring in JavaScript :)

Here is a comprehensive list of all the topics we'll be learning:

  1. What destructuring means

  2. Destructuring arrays

  3. Destructuring objects

  4. Default values

  5. Rest Opeator in Destructuring

  6. Destructuring in Functions

  7. Nested Destructuring

  8. Benefits of destructuring

Pretty simple, pretty easy let's break them down one by one, gather your focus and sit back relaxed make sure to have a tea/coffee with you as well β˜•πŸ’


PHD on Destructuring :)

What Destructuring Means?

  • Destructuring means extracting each and every element or property out of an array or object.

  • It's just like unpacking them and storing them in a separate variable.


Destructuring Arrays

  • Destructuring in Array means extracting out elements from an array.
// You have got an array named UsersArray, which contains 3 objects of users. You have to destructure the array between 3 variables named user1, user2, and user3. Then you have to print the name of each user in the console.

const UsersArray = [
  { name: "Uzumaki Naruto", age: 17 },
  { name: "Yeager Eren", age: 55 },
  { name: "Ryomen Sukuna", age: 1000 },
];

const [user1, user2, user3] = UsersArray;
console.log(user1.name);
console.log(user2.name);
console.log(user3.name);

// Uzumaki Naruto
// Yeager Eren
// Ryomen Sukuna
  • Look it is so simple, you just have to pass the variable names in square brackets and that is it this all it takes.

Destructuring Objects

  • Destructuring Objects means extracting out the properties from an object.
// You have got an object that properties name, age and city. You have to destructure the object and assign the properties to variables with the same name and log them as well

const person = {
  name: "John",
  age: 30,
  city: "New York",
};

const { name, age, city } = person;

console.log(name);
console.log(age);
console.log(city);


// John
// 30
// New York

Default Values

  • In Destructuring what happens is that you can have default values as well.

  • But default values only work if the result is undefined , it doesn't work on null.

const arr = []

const obj = {lastName: undefined, age: null}

const [item = 'Dumbbell'] = arr // item = Dumbbell

const {firstName = 'Eren'} = obj // firstName = Eren

const {lastName = 'Yeager'} = obj // lastName = Yeager

const {age = 19} = obj // age = null

Rest Operator in Destructuring

// Rest operator in Destructuing

const arr = ['Eren', 'Mikasa', 'Armen', 'Levi']

const obj = {founding: '300m+', colossal: '60m', eren: '15m'}

const [mainCharacter, ...otherCharacters] = arr
// mainCharacter = Eren
// otherCharacters = ['Mikasa', 'Armen', 'Levi']

const {tallestTitan, ...otherTitans} = obj
// tallestTitan = {founding: 300m+}
// otherTitans = {colossal: '60m', eren: '15m'}

See what happens is that we add ellipses (...) at the beginning of the variable name and it creates a new array or object and assigns rest values to it (all the values which are left in the array or object after destructing).


Destructuring in Functions

In functinons you can use destructuing to have many parameters by a single array/object or for default values

function greet({name, age = 80}) {
  console.log(`My name is \({name} and i am \){age} years old`)
}

greet({name: 'Madara', age: undefined})

This is how you can use destructuing and default parameters in functions, i won't show output that's your job :)

There is one more thing that you can do and that is rest parameters.

function multiply(...array) {
  return result.reduce((acc, value) => value * acc, 1)
}

consolel.log(multiply([1, 2, 3, 4, 5]))

Basically you can access indefinte amount of parameters in the form of array or objects.

Don't froget to run this one as well :)


Nested Destructuring

Nested Destructuring is simple, no such rocket science you just destructure something and inside that destructure again.

const character = {
  name: 'Eren Yeager',
  age: 19,
  friends: ['Mikasa', 'Armen']
}

const {name, age, friend: [girlfriend, bestfriend]} = character

Don't mind the example πŸ’€

See how easy nested destructuring was...


Benifits of Destructuring

Destructuring let's you extract out a value or property from an array or object in a different variable.

  • Default Values: We can handle deault values in destructuring thus, making it easier to handle APIs, or DBs.

  • Readability: The code becomes easier and more readable to understand.

  • Consiceness: The code becomes more consice and less error prone and in case there is an error it becomes easier to debug.

Assignment: There are more benifits of Destructuing but that's an assignment for you guys to think about.


Wrap Up!

That was it from my side guys, glad that you made it so far here...

Congratulations you just learnt a new topic in 4-5 minutes of reading :)

I'll catch you up in other blog go ahead do some code and enjoy sipping your coffee/tea β˜•πŸ’

JavaScript: Everything you should know

Part 15 of 26

This is your ultimate guide towards JavaScirpt, this series of articles include - JavaScript Operators: The Basics You Need to Know - Understanding Variables and Data Types in JavaScript - Template Literals in JavaScript - Control Flow in JavaScript: If, Else, and Switch Explained - Array Methods You Must Know - JavaScript Arrays 101 - Function Declaration vs Function Expression: What’s the Difference? - Arrow Functions in JavaScript: A Simpler Way to Write Functions - Understanding Objects in JavaScript - Spread vs Rest Operators in JavaScript - Destructuring in JavaScript - Map and Set in JavaScript - Understanding Object-Oriented Programming in JavaScript - Understanding the this Keyword in JavaScript - The new Keyword in JavaScript - The Magic of this, call(), apply(), and bind() in JavaScript - Array Flatten in JavaScript - String Polyfills and Common Interview Methods in JavaScript - Synchronous vs Asynchronous JavaScript - Callbacks in JavaScript: Why They Exist - JavaScript Promises Explained for Beginners - Promise Methods Explained: CID Analogy - Async/Await in JavaScript: Writing Cleaner Asynchronous Code - Error Handling in JavaScript: Try, Catch, Finally - JavaScript Modules: Import and Export Explained - The Part of Events You Never See The following 26 articles and topics are covered

Up next

Deep Dive in Error Handling in JavaScript

What are we gonna Study? So, today in this blog we will be studying about error handling more specifically, the topics listed below: What errors are in JavaScript Using try and catch blocks The fin

More from this blog

L

Learning Tech

61 posts

A Blog with dozens of articles on different langauges as well as frameworks, This isn't just for you to learn, i crafted it thinking that this could be my future reference as well

It covers Networking, Web Development, Mobile Developement and very soon GenAI too!