Skip to content

Latest commit

 

History

History
169 lines (131 loc) · 3.05 KB

File metadata and controls

169 lines (131 loc) · 3.05 KB

ES6 Spread Operator ( ... )

Syntax

  1. For array literal
[...iterableObj, '4', 'five', 6];
  1. For object literal (new in ECMAScript 2018)
let objClone = { ...obj };

Spread operator for array literal

  • With spread operator becomes easier to create/edit/delete array elements instead of using push, slice and contact.

Copy of array

Q1

  • Copy of names array using ES5
const names = ['a', 'b'];

Q1-Answer

const names = ['a', 'b'];
const copy1 = names.slice();
console.log(names); 
console.log(copy1);

Q2

  • Copy of names array using ES6
const names = ['a', 'b'];

Q2-Answer

  • spread operator
const names = ['a', 'b'];
const copy2 = [...names];
console.log(names); 
console.log(copy2);

Combine Array

Q3

  • Adding 'c' in names array in ES5
const names = ['a', 'b'];

Q3-Answer

  • push()
const names = ['a', 'b'];
names.push('c'); 
console.log(names); 

Conbine two arrays

Q4

  • Adding 'd' in names array and keep names as original and create new array
const names = ['a', 'b'];

Q4-Answer

  • concat() - adding an item AND create new array
const names = ['a', 'b'];
const newArray = names.concat('d');
console.log("original: " + names);
console.log("newArray: " + newArray);

Merge elements

Q5

  • Adding arr1 in arr2 between btw 'one' and 'four'
const arr1 = ['two', 'three'];
const arr2 = ['one', 'four'];

Q5-Answer

const arr1 = ['two', 'three'];
const arr2 = ['one', ...arr1, 'four'];
console.log(arr1); //[ 'two', 'three' ]
console.log(arr2); //[ 'one', 'two', 'three', 'four' ]

Spread operator for object

Install babel plug-in for spread operator

babel/plugin-transform-spread

npm install --save-dev @babel/plugin-transform-spread

Add plug-in into .babelrc file

.babelrc

{
  "plugins": ["@babel/plugin-transform-spread"]
}

Example

1. Add new property in user object

const user = {
  name: 'Jen',
  age: 24
}

// Add new property
console.log({
  ...user,
  location: 'New York'
});
//{name: "Jen", age: 24, location: "New York"}

2. Override existing property age=27

console.log({
  ...user,
  location: 'New York',
  age: 27
});
//{name: "Jen", age: 27, location: "New York"}

3. Override existing property from age=27 to age=24

// Override existing property
console.log({
  age: 27,
  ...user,
  location: 'New York',
});
//{age: 24, name: "Jen", location: "New York"}