Blog

Descructured Array Examples
Posted on September 10, 2020 in JavaScript by Matt Jennings

Array destructuring is the assignment part of a variable, not the declaration part.

Destructured Array Code Examples

// Non-destructured code
function data() {
  return [1,, 3,4,5];
}

var tmp = data();
var first = tmp[0];
var second = tmp[1];
var third = tmp[2];

console.log(second); // undefined

function data2() {
  return [1,, 3,4,5];
}

// Destructed code
var [
  first2, 
  // second2 is assigned 10
  // ONLY if it's value equals undefined
  // (NOT include null)
  second2 = 10, 
  third2,
  // Rest syntax which converts
  // comma separated values in an array into
  // another array
  ...rest
] = data2();

console.log(second2); // 10

console.log(rest); // [4,5]

// Destructure example 2
function data3() {
  return [1, 2, 3];
}

var tmp;
var [
  first,
  second,
  third,
  ...forth    
] = tmp = data3();

console.log(forth); // []

console.log(tmp); // [1, 2, 3, ]

// Destructure example with leaving an emtpy space so that 
// an array element isn't assigned to a variable
function data4() {
  return [1,2,3];
}

var tmp;
var [
  first,
  ,
  third,
  ...fourth
] = tmp = data4();

console.log(first);  // 1
console.log(third);  // 2
console.log(fourth); // []

// Destructing way using an Array to Swap Values
var x = 10;
var y = 20;
[x, y] = [y, x];
console.log(x); // 20
console.log(y); // 10

 

Leave a Reply