Best javascript Destructuring assignment tutorials and examples

This tutorial covers es6 destructuring assignment examples ES6 introduced a new feature called destructuring assignment.

You can check my previous posts on es6 another post.

What is Destructuring assignment in javascript

This is a syntax change to extract the data from objects or arrays or nested iterable objects and assign them to variables.

Syntax

let [variables] = array / object / nestedobject;

It contains two parts, The first part is the right side of o equal sign ie iterable objects The second part is left side with an equal sign i.e variables.

Arrays/objects can be a break and destruct, and assign 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.

Before 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 them 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;
console.log(firstElement)
console.log(secondElement)

Output the above code execution is

destructuring
assignment

Array Destruction assignment example

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

Here is a basic Example

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

destruction assignment with Default values

if the number of variables declared on the left side is more than many elements on 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 is found in the array, Default values are initialized.

let arrayExample = ["destructuring", "assignment"]

const [var1 = 'defaultone', var2, var3 ='defaulthree'] = arrayExample;

console.log(`var1: ${var1}, var2: ${var2}, var1: ${var2}`);

Output is

var1: destructuring, var2: assignment, var1: assignment

var1 and var3 are assigned with default values, the array has only two index elements, the first element is assigned to var1, var2 is assigned with the second value, and var3 is assigned with a default value.

How to skip variables initialization in destructuring assignment

Sometimes, We want to skip the variables with empty by a comma. These are called unknown variables.

let [, , testvar] = ["one", "two", "three", "four"];
console.log(testvar);

In the above example, Two commas are placed, Each comma represents a single unknown variable output is

three;

javascript Object Destruction assignment Examples

The object is a composition of different attributes stored 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 employee.id, Please note, Id does not mention 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 on 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 the id property is not found in the object, the newId value is assigned with a default value. In this case id property, not an existing object. Output is 12

var { id: newId = 12 } = employee;
console.log(newId);      // 11

a local variable is created with an 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 the 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 Employee.id newId is initialized with value 11 If you access the 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 assignment in javascript

An object has a child object as shown below example.

var employee = {
    id: 11,
    name: "Tom",
    address: {
        city: 'NewYork',
        Country:'USA'
    }
};
var { address: { city} } = employee;
console.log(city);      // outputs Newyork
console.log(address);       // error: address is undefined

Here, the city local variable is created and assigned with New York, the address variable is not created and serves as the locator for mapping child elements. Destructuring looping/iteration

Object. entries method is used to destructure/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. It uses to assign 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);
}
getEmployee(employee);

Conclusion

We have learned different arrays and object examples with the destructuring assignment.