Saturday, August 18, 2018

ES 6 features - destructuring assignment examples| Learn Es6 tutorials

Es6 introduced a new feature called destructuring assignment. This is a syntax change to extract the data from objects or array and assigned to variables.

Destructuring assignment Basics

First get the right side of the equal sign. ie arrays/objects and break or destruct it, and assign this each part to each corresponding variable on the left side of the equal sign. Here Variables are already existed or can be created using let const and var keywords.

Prior to es6 and previous javascript versions

Declared and initialized an array with two values.
let arrayExample = ["destructuring", "assignment"]
Now we want to retrieve the values from an array and assign to variables, Used index with getting an element from an array
let firstElement = arrayExample[0];
let secondElement = arrayExample[1];
The same code can be rewritten with destructuring assignment syntax as follows
let arrayExample = ["destructuring", "assignment"]
let [firstElement, secondElement] = arrayExample;
Output the above code execution is

Array Destruction assignment

Arrays are a group of elements store under a name. By now you understand destruction feature. Array destruction, left the side of the element is an array value and breaks the array and assign to the same variables order with the same array index.

Basic Example

var var1, var2;
[var1,var2] = [15, 12];
console.log(var1); // 15
console.log(var2); // 12

Default values with destruction

if the number of variables declared on the left side is more than a number of elements in the right side, then excess items are not assigned. variables with default values are mapped to the values from Array. if no matching index element found in array, Default values are initialized.
const [var1 = 'defaultone', var2, var3 ='defaulthree'] = arrayExample;
console.log(`var1: ${var1}, var2: ${var2}, var1: ${var2}`);
Output is
var1: one, var2: undefined, var3: defaulthree
var1 and var3 has default parameter values,
the array has only one index element, the First element is assigned to var1, var2 is assigned with undefined, var3 assigned with a default value

Skip variables initialization

let [, , testvar] = ["one", "two", "three", "four"];
console.log( testvar ); 
In the above example, Two commas are placed, Each comma represent single unknown variable
output is

Object Destruction assignment Examples

The object is a composition of different attributes store under a single name. The right-hand side of an equal operator is Object and destruct/break it and assigned with variables
In the below code, the simple variable is declared assigned to the value, Please note, Id is not mentioned on the right-hand side in a code Using destruction.
var employee = {
    id: 12,
    name: "Frank"
var { id } = employee; 
var { name } = employee;
console.log(id);      // outputs 12
console.log(name);      // outputs Frank

Object Default values

Variables declared in the left side should be declared with default values
var employee = {
    id: 11,
    name: "Tom"
var newEmployee = {};
var { id: newId = 12 } = newEmployee;
console.log(newId);      // 12

Here newEmployee is empty and local variable newId is created and the default value is 12, if id property not found in the object, the newId value is assigned with a default value. In this case id property, not existing object. Output is 12
var { id: newId = 12 } = employee;
console.log(newId);      // 11

a local variable is created with id value from the object, property id exists in the object, so id value is assigned to local variable output is 11 for new id

new variable names assignment

Normally you create a same variable name of the object properties.
In this example, You are going to create a new variable with a different name, assigned with object property
It creates a new local variable newId that is assigned with
newId is initialized with value 11
If you access id variable, throws an error 'Uncaught ReferenceError: id is not defined'
var employee = {
id: 11,
name: "Tom"
var { id: newId } = employee;
console.log(newId); // "Identifier"
console.log(id); // outputs 12

Nested Object destruction

An object has child object as shown below example
var employee = {
    id: 11,
    name: "Tom",
    address: {
        city: 'NewYork',
var { address: { city} } = employee;
console.log(city);      // outputs Newyork
console.log(address);       // error: address is undefined
Here, city local variable is created and assigned with NewYork, address variable is not created and serving the locators for mapping child elements.
Destructuring looping/iteration

Object.entries method is used to destructuring/break the key and pair values of an object during an iteration of for loop
var employee = {
    id: 51,
    name: "John",
for (let [key, value] of Object.entries(employee)) {
  console.log(`${key}:${value}`); // id:51 name:John

REST operator with the destructuring assignment

Rest/Spread operators introduced in Es6 with the new syntax. This can be used to assign to variables with destructing
let [var1, var2, ...varRest] = ["one", "two", "three", "four","five"];
console.log(var1); // one
console.log(var2); // two
console.log(varRest[0]); // three
console.log(varRest[1]); // four
console.log(varRest[1]); // five
console.log(varRest.length); // 3

destructuring parameters from the object passed a function's parameters

destructuring the id and name from an object that is passed as an argument to function.
var employee = {
    id: 11,
    name: "Tom",
function getEmployee({name, id}) {
  console.log('id: '+id + '  name: ' + name);

Related article