by Sai gowtham

Destructuring function arguments in JavaScript (es6)

In es6 we got a more powerful feature which is the destructuring syntax.

What is Destructuring ?

Destructuring syntax helps us extract the values from the arrays or objects into their own named variables.

Let’s see an example without using destructuring syntax.

function userInfo(user){

   const name = user.name;   const age = user.age;
}

userInfo({name:"gowtham",age:22})

In the above code, we extracted the object data by using dot notation user.name but you can see its already hard to declare a new variable for every property in the object we have.

Destructuring function arguments example

Now, we are rewriting the same code by using the destructuring syntax.

function userInfo({name,age}){
   console.log(name,age)

}

userInfo({name:"gowtham",age:22})

In the above code, we unpacked the object properties inside the function parameter by using destructuring syntax {name, age}.

We improved our code so much by using destructuring.

The order of destructing the object properties doesn’t matter for example.

function userInfo({age,name}){
   console.log(name,age)

}

userInfo({name:"gowtham",age:22})

Here we extracted the age property first and name property second.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course