On this page
- 1 ES6: Spread operator
- 2 ES6: Spread operator
- 2.1 Description
- 2.2 Syntax
- 2.2.0.1 Introduction to the DOM
- 2.2.0.2 How to apply CSS to iframe?
- 2.2.0.3 JavaScript Map, Reduce, and Filter
- 2.2.0.4 JavaScript Concepts Everyone Should Learn!
- 2.2.0.5 JavaScript: localStorage and sessionStorage
- 2.2.0.6 JavaScript: Array functions/methods
- 2.2.0.7 JavaScript: Array map() Method
- 2.2.0.8 Promise in JavaScript with example
- 2.2.0.9 JavaScript: FormData
- 2.2.0.10 JavaScript: How ES6 Arrow Function Can Help You
- 2.2.0.11 ES6: Spread syntax
- 2.2.0.12 ES6: Introduction
- 2.2.0.13 JavaScript: Scope and the Variable this
- 2.2.0.14 JavaScript: Get Element
- 2.2.0.15 JavaScript: JSON (JavaScript Object Notation)
- 2.2.0.16 JavaScript: Application programming interface (API)
- 2.2.0.17 Javascript : Date & Time Program
- 2.2.0.18 JavaScript: What is AJAX?
- 2.2.0.19 JavaScript: Getting started
- 2.3 Leave A Comment Cancel reply
ES6: Spread operator
ES6: Spread operator
Spread syntax (…) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
function sum(x, y, z) { return x + y + z; } const numbers = [1, 2, 3]; console.log(sum(...numbers)); // expected output: 6 console.log(sum.apply(null, numbers)); // expected output: 6
Description
Spread syntax can be used when all elements from an object or array need to be included in a list of some kind.
In the above example, the defined function takes x, y, and z as arguments and returns the sum of these values. An array value is also defined.
When we invoke the function, we pass it all the values in the array using the spread syntax and the array name — …numbers.
If the array contained more than three numbers, e.g. [1, 2, 3, 4], then it would still work fine, except that all four would be passed, but only the first three would be used unless you added more arguments to the function, e.g.:
function sum(x, y, z, n) { return x + y + z + n; }
The above example is somewhat rigid; the real value in spread syntax is that it works with the same value, no matter how many elements are contained in the object, array, etc.
It is commonly used when you want to add a new item to a local data store, or display all stored items plus a new addition. A very simple version of this kind of action could look like so:
let numberStore = [0, 1, 2]; let newNumber = 12; numberStore = [...numberStore, newNumber];
Syntax
For function calls:
myFunction(...iterableObj); // pass all elements of iterableObj as arguments to function myFunction