- For array literal
[...iterableObj, '4', 'five', 6];- For object literal (new in ECMAScript 2018)
let objClone = { ...obj };- With spread operator becomes easier to create/edit/delete array elements instead of using
push,sliceandcontact.
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);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); 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);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' ]-
ES6 implemented spread operator for array literal but not object literal. It is now in proposal stage and we will be able to use in ES8.
-
Babel plug-in is available to use in React.js. object-rest-spread
npm install --save-dev @babel/plugin-transform-spread.babelrc
{
"plugins": ["@babel/plugin-transform-spread"]
}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"}