Spread operator

Defination

The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.

Syntax

1
// For function calls:
2
myFunction(...iterableObj);
3
// For array literals:
4
[...iterableObj, 4, 5, 6];
5
// For object literals (new in ECMAScript; stage 3 draft):
6
let objClone = { ...obj };
Copied!

Examples

1
// Function
2
function myFunction(x, y, z) { }
3
var args = [0, 1, 2];
4
myFunction(...args);
5
// Array
6
var parts = ['shoulders', 'knees'];
7
var lyrics = ['head', ...parts, 'and', 'toes'];
8
// ["head", "shoulders", "knees", "and", "toes"]
9
// Object
10
var obj1 = { foo: 'bar', x: 42 };
11
var obj2 = { foo: 'baz', y: 13 };
12
13
var clonedObj = { ...obj1 };
14
// Object { foo: "bar", x: 42 }
15
16
var mergedObj = { ...obj1, ...obj2 };
17
// Object { foo: "baz", x: 42, y: 13 }
Copied!

Usage

1
function todos(state = [], action) {
2
switch (action.type) {
3
case ADD_TODO:
4
return [
5
...state,
6
{
7
text: action.text,
8
completed: false
9
}
10
]
11
case TOGGLE_TODO:
12
return state.map((todo, index) => {
13
if (index === action.index) {
14
return Object.assign({}, todo, {
15
completed: !todo.completed
16
})
17
}
18
return todo
19
})
20
default:
21
return state
22
}
23
}
Copied!

References