Destructuring assignment in ES6 for more clarity

ES6 introduces the Destructuring assignment that allows javascript developers to assign items of arrays or properties of objects to any individual variables. While the syntax is more simplified it exhibits more clarity that the traditional property access. 
Here is how you would extract items from an array in ES5:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var animals = [ 'dog' , 'lion' , 'cat' ]
var a = animals [ 0 ] ;
var b = animals [ 1 ] ;
var c = animals [ 2 ] ;
console. log ( a ) ; //dog
console. log ( b ) ; //lion
console. log ( c ) ; //cat
var animals = ['dog','lion','cat'] var a = animals[0]; var b = animals[1]; var c = animals[2]; console.log(a); //dog console.log(b); //lion console.log(c); //cat
var animals = ['dog','lion','cat']
var a = animals[0];
var b = animals[1];
var c = animals[2];
console.log(a); //dog
console.log(b); //lion
console.log(c); //cat

In ES6, this is more easy and simplified: 

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var [ a,b,c ] = [ 'dog' , 'lion' , 'cat' ] ;
console. log ( a ) ; //dog
console. log ( b ) ; //lion
console. log ( c ) ; //cat
var[a,b,c] = ['dog','lion','cat']; console.log(a); //dog console.log(b); //lion console.log(c); //cat
var[a,b,c] = ['dog','lion','cat'];
console.log(a); //dog
console.log(b); //lion
console.log(c); //cat

Destructuring works with arrays and objects. Essentially you can assign anything iterable on the right-side to anything at the left-side.

Array Destructuring

Here we’ll see how we can utilize the Destructuring Assignment for an array.

The assignment is separate from the declaration

We can assign the value to the variable by destructuring the variable from its declaration.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var a, b;
[ a, b ] = [ 1 , 2 ] ;
console. log ( a ) ; // 1
console. log ( b ) ; // 2
var a, b; [a, b] = [1, 2]; console.log(a); // 1 console.log(b); // 2
var a, b;
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2

Default values

If you are not sure that the array may contain all required values, provide default variables while destructuring.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var [ a= 5 , b= 7 ] = [ 1 ] ;
console. log ( a ) ; // 1
console. log ( b ) ; //
var [a=5, b=7] = [1]; console.log(a); // 1 console.log(b); //
var [a=5, b=7] = [1];
console.log(a); // 1
console.log(b); //

Swapping variables

Traditionally, swapping two values requires a temporary variable. However, a single destructuring expression does this without the need for an extra variable.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var a = 1 ;
var b = 3 ;
[ a, b ] = [ b, a ] ;
console. log ( a ) ; // 3
console. log ( b ) ; // 1
var a = 1; var b = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); // 1
var a = 1;
var b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1

Ignoring values

Ignoring a value from an array is as simple as inserting white space in place of the variable for that specific value at the right-hand side.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var [ a, , b ] = [ 1 , 2 , 3 ] ;
console. log ( a ) ; // 1
console. log ( b ) ; // 3
var [a, , b] = [1, 2, 3]; console.log(a); // 1 console.log(b); // 3
var [a, , b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // 3

Rest in array destructuring

While destructuring an array, you can assign the first few items to individual variables. For the rest, you can create a new array.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var [ a, b, …rest ] = [ 1 , 2 , 3 , 4 , 5 , 6 ] ;
console. log ( a ) ; // 1
console. log ( b ) ; // 2
console. log ( rest ) ; // [3,4,5,6]
var [a, b, …rest] = [1, 2, 3, 4, 5, 6]; console.log(a); // 1 console.log(b); // 2 console.log(rest); // [3,4,5,6]
var [a, b, …rest] = [1, 2, 3, 4, 5, 6];
console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3,4,5,6]

The syntax is a spread operator. More detail about spread operators is available here.

Unpackaging an array passed to a function parameter

Destructuring can unpack array values to use them inside a function where an array is passed as a parameter.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var testArray = [ 1 , 2 , 6 , 3 ] ;
testingArray ( testArray ) ;
function testingArray ([ a,b ]){
console. log ( a ) ;
console. log ( b ) ;
}
var testArray = [1,2,6,3]; testingArray(testArray); function testingArray([a,b]){ console.log(a); console.log(b); }
var testArray = [1,2,6,3];
testingArray(testArray);
function testingArray([a,b]){
  console.log(a);
  console.log(b);
}

Object Destructuring

The Destructuring assignment is also used for objects. We can easily unpack object properties and assign them to new variables. Let’s see the implementation of a destructuring assignment for objects.

Basic Assignment

While destructuring an object, the variable names should be the same as the object properties. Here is an example of a basic assignment expression for objects:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var o = { p: 42 , q: true } ;
var { p, q } = o;
console. log ( p ) ; // 42
console. log ( q ) ; // true
var o = {p: 42, q: true}; var {p, q} = o; console.log(p); // 42 console.log(q); // true
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true

An assignment without a declaration

We can destructure object properties and assign them to the variable, while separately declaring the variable.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var a, b;
({ a, b } = { a: 1 , b: 2 }) ;
console. log ( a ) ; // 1
console. log ( b ) ; // 2
var a, b; ({a, b} = {a: 1, b: 2}); console.log(a); // 1 console.log(b); // 2
var a, b;
({a, b} = {a: 1, b: 2});
console.log(a); // 1
console.log(b); // 2

While using object literals for a destructuring assignment without a declaration, parentheses (…) are required around the assignment statement. Brackets {..} on the left-hand side considered as a block and not an object literal.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{ a, b } = { a: 1 , b: 2 } ; // this would be an invalid statement without parentheses.
{a, b} = {a: 1, b: 2}; // this would be an invalid statement without parentheses.
{a, b} = {a: 1, b: 2}; // this would be an invalid statement without parentheses.

Assigning new variable names

We can assign a different name than the property to a variable while destructuring an object.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var o = { p: 42 , q: true } ;
var { p: foo, q: bar } = o;
console. log ( foo ) ; // 42
console. log ( bar ) ; // true
var o = {p: 42, q: true}; var {p: foo, q: bar} = o; console.log(foo); // 42 console.log(bar); // true
var o = {p: 42, q: true};
var {p: foo, q: bar} = o;
console.log(foo); // 42
console.log(bar); // true

Default values

While destructuring an object we can provide the default values for undefined properties of that particular object.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var { a = 10 , b = 5 } = { a: 3 } ;
console. log ( a ) ; // 3
console. log ( b ) ; // 5
var {a = 10, b = 5} = {a: 3}; console.log(a); // 3 console.log(b); // 5
var {a = 10, b = 5} = {a: 3};
console.log(a); // 3
console.log(b); // 5

Rest in object destructuring

Same as an array we can assign the first few properties of the object to variables, and with the rest of the properties, we can create a new object.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let { a, b, …rest } = { a: 10 , b: 20 , c: 30 , d: 40 }
console. log ( a ) ; // 10
console. log ( b ) ; // 20
console. log ( rest ) ; // { c: 30, d: 40 }
let {a, b, …rest} = {a: 10, b: 20, c: 30, d: 40} console.log(a); // 10 console.log(b); // 20 console.log(rest); // { c: 30, d: 40 }
let {a, b, …rest} = {a: 10, b: 20, c: 30, d: 40}
console.log(a); // 10
console.log(b); // 20
console.log(rest); // { c: 30, d: 40 }

Unpackaging an object passed to a function parameter

When an object is passed to the function as a parameter, we can destructure the required object properties to use them inside the function.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function studentFullName ({ fullName: { firstName, lastName }}){
return `$ { firstName } $ { lastName } `;
}
var student = {
id: 42 ,
displayName: ‘Robin’,
fullName: {
firstName: ‘Robin’,
lastName: ‘Wine’
}
} ;
console. log ( studentFullName ( student )) ; // Robin Wine
function studentFullName({fullName: {firstName, lastName}}){ return `${firstName} ${lastName}`; } var student = { id: 42, displayName: ‘Robin’, fullName: { firstName: ‘Robin’, lastName: ‘Wine’ } }; console.log(studentFullName(student));// Robin Wine
function studentFullName({fullName: {firstName, lastName}}){
  return `${firstName} ${lastName}`;
}
var student = {
  id: 42,
  displayName: ‘Robin’,
  fullName: {
    firstName: ‘Robin’,
    lastName: ‘Wine’
  }
};
console.log(studentFullName(student));// Robin Wine

Conclusion

Destructuring assignments make it easy to extract the required values or properties from any iterable. Destructuring assignment destructurizes the array or object by copying the items into variables, without modifying the array or object itself and that’s the beauty of it.
If you found this post useful, here are a few more you may like:

Learn More about Encora

We are the software development company fiercely committed and uniquely equipped to enable companies to do what they can’t do now.

Learn More

Global Delivery

READ MORE

Careers

READ MORE

Industries

READ MORE

Related Insights

Enabling Transformation in Hospitality through Technology-Led Innovation

As the exclusive sponsor of the 2024 Hotel Visionary Awards, we support organizations leading ...

Read More

Key Insights from HLTH 2024: The Future of Patient-Centered Healthcare

Discover key insights from HLTH 2024 on digital health, AI in diagnostics, data interoperability, ...

Read More

Data-Driven Engineering: Transforming Operations and Products from Insight to Impact

Discover how data-driven engineering transforms operations and product development, enhancing team ...

Read More
Previous Previous
Next

Accelerate Your Path
to Market Leadership 

Encora logo

Santa Clara, CA

+1 669-236-2674

letstalk@encora.com

Innovation Acceleration

Speak With an Expert

Encora logo

Santa Clara, CA

+1 (480) 991 3635

letstalk@encora.com

Innovation Acceleration