ES6 in Depth
  • Introduction
  • Installation
  • Block Scope
    • Constant
    • Use cases
  • Template String
    • New String Methods
    • Tagged Template Literal
  • New Number Methods
  • Arrow Function
    • Default Parameters
    • Lexical This Scope
    • Where not to use arrow function
  • Object Enhancement
  • New Array Methods
    • For Of
  • Spread Operator
  • Destructuring
    • Array Destructuring
  • Class
  • Symbols
  • New Data Structures
    • Set
    • Map
    • WeakSet
    • WeakMap
    • Iterators
    • Generators
  • Promise
  • Import Export
Powered by GitBook
On this page
  • Use Case 1
  • Use Case 2
  • Use case 3 - Create copy of array

Was this helpful?

Spread Operator

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

Use Case 1

var arr1 = [1,2,3];
var arr2 = [4,5,6];

// arr1.push(arr2) or [1,2,3, arr2]
// console.log(arr1); //  [1, 2, 3, [4, 5, 6]]

arr1.push(...arr2)
console.log(arr1); //   [1, 2, 3, 4, 5, 6]

Use Case 2

function display(a,b,c){
    console.log(a+b+c); //  60
}

display(...[10,20,30]);

Use case 3 - Create copy of array

var arr1 = [1,2];
var arr2 = [3,4];

var newArr = [...arr1, ...arr2];
var arrCopy = [...newArr]; // Old way [].concat(newArr)

arrCopy[0] = 100;

console.log(arrCopy); [100,2,3,4]
console.log(newArr); [1,2,3,4]
PreviousFor OfNextDestructuring

Last updated 4 years ago

Was this helpful?