The Spread Operator

Description

It allows you take an array and spread them into individual elements. It is represented by three dots like so: (...)

Example 1:

var tea = ["black", "green", "lemon"];
console.log(tea);
//Result will be; ["black", "green", "lemon"].

//Adding the spread operator
var tea = ["black", "green", "lemon"];
console.log(...tea);
//Result will be; black green lemon. It takes the array and displays them as individual components.

Example 2:

var nums1 = [1,2,3];
var nums2 = [4,5,6];

//If nums1 is poped into nums2 like so;
var nums2 = [nums1,4,5,6];
console.log(nums2);
//Expected result will be; [1,2,3,4,5,6].
//Result will be; [Array[3], 4, 5, 6] --This is an array within an array.

//Using the spread operator;
var nums2 = [...nums1,4,5,6];
console.log(nums2);
//Result will be; [1,2,3,4,5,6].

Example 3:

var nums = [3,5,7];

function addNums(a,b,c){
    console.log(a+b+c);
}
addNums(nums)
//If nums was passed when calling the function, result will be; 3,5,7undefinedundefined.

//Using the spread operator;
var nums = [3,5,7];

function addNums(a,b,c){
    console.log(a+b+c);
}
addNums(...nums)
//Result will be 15 which is the addition of 3,5 and 7.

No Comments Yet