Destructuring arrays

  1. var nums = [1, 2, 3, 4, 5];
  2. var [first, second,,,,fifth] = nums;
  3. log(first, second, fifth); // 1, 2, 5

Swapping variables

how to swap variables without using a temp var

  1. var a = 1, b = 2;
  2. // The Old Way
  3. var temp = a, a = b, b = tmep;
  4. // The New Way
  5. [b, a] = [a, b];

Method signature

  1. var nums = [1, 2, 3, 4];
  2. doSomething(nums);
  3. function doSomething([first, second, ...others]){
  4. log(first); //logs 1
  5. log(second); //logs 2
  6. log(others); //logs [3, 4]
  7. }

Nested Destructuring Array

  1. var nums = [1, 2, [30, 40, [500, 600]]];
  2. var [one,,[thirty,,[,sixhundert]]] = nums;

Pattern Errors

  1. let [x] = [2, 3] // x = 2
  2. let [x] = {'0': 4} // x = 4
  3. let [x, y, z] = [1, 2] // throw

Refutable

  1. // Entire Pattern is Refutable
  2. let ?[x, y, z] = [1, 2] // x = 1, y = 2, z = undefined
  3. // Only 'z' is Refutable
  4. let [x, y, ?z] = [1, 2] // z = 1, y = 2, z = undefined