Spreading Values
Version: ES2015 (array, function), ES2018 (object)
Level: Beginner
Spreading is an operation that can be performed on values in JavaScript to copy their properties into another location. Spread values are denoted by a preceding 3 dots (...
). There are three kinds of spreading:
- Array spreading
- Function spreading
- Object spreading
Array spreading is performed in array literals ([]
) and copies values shallowly from any other iterable value into the new array. Each iterable value in the spread value is then placed as individual elements within the array.
let missing = [3, 4];
let caughtThemAll = [1, 2, ...missing, 5];
console.log(caughtThemAll); // [1, 2, 3, 4, 5]
Function spreading is performed in function call argument lists and copies values shallowly from any other iterable value into the list of arguments passed to the function call. The use of spreading in functions effectively removes the need for the apply()
Function method which allows arrays to be used as argument lists.
function goForthAndMultiply (a, b, c) {
return a * b * c;
}
let numbers = [2, 3, 7];
let result = goForthAndMultiply(...numbers);
console.log(result); // 42 (2 * 3 * 7)
// same as
goForthAndMultiply.apply(null, numbers);
Object spreading is performed in object literals ({}
) and copies enumerable, non-inherited properties shallowly from any other value into the new object.
let defaultOptions = { name: 'volume', value: 0 };
let userOptions = { value: 11 };
let options = { ...defaultOptions, ...userOptions };
console.log(options); // { name: 'volume', value: 11 }
Spreading objects is unique in that it copies keys and values and it doesn’t require an iterable as was the case with array and function call spreading. In fact any value can be spread in an object, even null
and undefined
, and no error will be thrown. If you try to spread a non-iterable (such as null
and undefined
) into an array or a function call, you will get an error.
let caughtNothing = [ ...null ]; // TypeError: not iterable
goForthAndMultiply(...null); // TypeError: not iterable
let optionless = { ...null }; // Ok, = {}
More info: