- ES6 provides another useful operator called spread operator to work with Array.
- Spread operator is represented by 3 dots prefixed with a variable name.For example …fruitArray .
- In this demo, “We will learn to use spread operator by an example”.
- Spread operator is similar to an inline function which expand it self on the called position.
- The following code shows 2 students array mathStudents and lawStudents containing few student names.By using spread operator we are combing it to a single array.In the later part of the code a summation() method is declared which takes a spread array as input parameter and iterate over it and returns the total sum by adding each item present in the spread array.
var mathStudents = ["Sandeep","Sangeeta","Surabhi"]; var lawStudents = ["Sumanta","Rohan","Surendra"]; var allStudents= ["John", ...mathStudents,"Jack",...lawStudents]; console.log(allStudents); var numberArray= [12,21,32,40]; var summation = function(...items){ var sum = 0; items.forEach(function(item) { sum = sum+item; }); return sum; }; var result = summation(...numberArray); console.log(result);
- The output of the code can be found in the following embedded JSBIN link.
Traceur Compiling ES6 Spread Operator
Sandeep
A passionate Blogger and Developer.Love to code for web application using JavaScript.At present I am exploring the Web Component Specification.