Header Ads

Header ADS

Destructuring in js

 

Today’s topic is about destructuring. It’s a very professional ways to make your code cleaner and readable.😀




In simple terms it means to take variables from arrays or objects and make them local ones. You may be familiar with if you had an experience with react

Code:

const arr = [1,2,3]

 

//bad

const first  = arr[0]

const second = arr[1]

const third = arr[2]

 

//noiiiiice 

 const [first,second,third] =arr

 

 console.log({first,second,third})

Where the position between [] matches the value in the array.

Of course you can ignore a variable by using :

 const [first,,third] =arr

 

If you want to get the rest of variables in other array :

 const [first,...res] =arr

 

Or to set a default value in case of an error:

 const [first=0,second,third] =arr

 

  Ok, enough with arrays let’s see objects:

const person ={

    name :"mehdi",

    age:"23",

    hobby :"coding"

}

 

//bad

const name  = person.name

const age = person.age

const hobby = person.hobby

 

//noiiiiice 

 const {name,age,hobby} = person

 

 console.log({name,age,hobby})

 

Here we use {}, we can default value also. In this code we can’t change the name of proprieties, if we want we have to:

 const {name:myName,age,hobby} = person

 

so we use name as myName. This is so useful if we can’t use the propriety name as a variable name.

In case of nested object. It’s almost the same:

const person ={

    parent:{

        child:"a child"

    }

}

 

 const {parent:{child}} = person

 

You can also destructor in loops or in function parameters.

 const person ={

  name:"me"

}

function something({name}){

console.log(name)

}

 

something(person)

 

It’s a way awesome when working with objects.  Just using this simple syntax😍

Other benefits of using it , when you need to destructure an object but you don’t know the property name.

var rando;

 

const obj = {

     [rando]:2

}

 

const {[rando]:myRando } = obj

console.log(myRando)

 

Now the myRando variable will take the value of rando which is 2

Not bad huh?😎

Hope you liked. Please give me you feedbacks

No comments

Theme images by enot-poloskun. Powered by Blogger.