Javascript Es6 - Array Destructuring Assignment

Aug 13, 2022

1 min read

Write your own content on FeedingTrends
Write

Destructuring assignment feature in javascript provides an easy syntax to assign values of array element or object property to individual variables.

Array Destructuring Assignment

Consider this array

const numbers = [1, 4, 5, 10, 15]

If we want to assign the first two elements of array ( 1 and 4) to variables "firstValue" and "secondValue".

Before array destructuring assignment feature we need to do it in the following way

// Without array destructuring assignment
const numbers = [1, 4, 5, 10, 15]

firstValue = numbers[0]
secondValue = numbers[1]

console.log(firstValue)
console.log(secondValue)

Output:
1
4

With array destructuring feature you can use the following syntax to achieve the same

// With array destructuring assignment
const [firstValue, secondValue] = [1, 4, 5, 10, 15]

console.log(firstValue)
console.log(secondValue)

Output:
1
4

Destructuring with spread operator

After assigning the first two elements of array if we want to assign the remaining array elements to another variables we can do it in the following way using spread operator

const [first, second, ...remainingElements] = [1, 4, 5, 10, 15]

console.log(first)
console.log(second)
console.log(remainingElements)

Output:
1
4
[5, 10, 15]

Assign default value

We can assign default value to a variable if the element is not present in the array

const [first, second, third = -1] = [1, 4]

console.log(first)
console.log(second)
console.log(third)

Output:
1
4
-1

Nested Array

We can use destructuring assignment with nested arrays also

function getNestedArray() {
  return [ "James", "6ft", ["Volvo", "BMW"]]
}

const [name, height, [ ownedCar1, ownedCar2]] = getNestedArray()

console.log(name)
console.log(height)
console.log(ownedCar1)
console.log(ownedCar2)

Output:
James
6ft
Volvo
BMW

If you like this blog do share it with others and give a like and follow me for more.

Write your own content on FeedingTrends
Write