Welcome Guest! (App Version 3.1)

websitnero logo name

Destructuring

Destructuring in ES6

Destructuring comes in ES6 helping taking out pieces or fragments of data from complete array or object. It is most helpful in cases when large amount of data is passed to a function but it only needs to work with some key-values or items rather than full array or object.

When used inside functions, destructuring in a single line creates variables and also assigns them values right from the objects or arrays passed to it.

Look at the example below:

obj1 = {
  name: "Peter Martin",
  age: 29,
  city: 'New York',
  country: 'USA',
  salary: '$30000',
  color: 'blue'
}

function increaseAge(someObj, val){
  {age} = someObj;
  return age+val;
}

Output: result is '34'

Explaination: Now, this is a classic example where the whole object is passed but your function doesn't need all that data. You only need to work with the 'age' key-value pair. So, destructuring helps in picking out only the data that you require and leave the rest.

See another example:

obj1 = {
  name: "Peter Martin",
  age: 29,
  city: 'New York',
  country: 'USA',
  salary: '$30000',
  color: 'blue'
}

function printDetail(someObj, message){
  let {name, city, country, color} = someObj;
  return (`${message} ${name}. You live in ${city}, ${country}. Your favorite color is ${color}`);
}

printDetail(obj1, 'Hello'); 

Output: "Hello Peter Martin. You live in New York, USA. Your favorite color is blue"

Explaination: By destructuring we are extracting and at the same time creating local variables named 'name, city, country and color'. Then we are using ES6 template literal to make use of the newly created variables along with text data to print the required information.

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.