Rest and Spread

//Example
function addNumbers(numbers) {
    return numbers.reduce(function(sum,number){
        return sum + number;
    },0);
}

addNumbers([1,2,3,4,5]); -> 15

//What if we want to sum the numbers but they were not an array, like multiple parameters
addNumbers(1,2,3,4,5,6,7); //We can use the rest operator (...) 
function addNumbers(...numbers) {
    return numbers.reduce(function(sum,number){
        return sum + number;
    },0);
}

//More example
const defaultColours = ['red','green']; 
const userFavoriteColours = ['orange', 'yellow'];

//If we want to join default colours and userFav, we can use the 'concat' method
defaultColours.concat(userFavoriteColours); -> ["red", "green", "orange", "yellow"]

//Or we can use the 'spread' operators: 
[...defaultColours, ...userFavoriteColours ]; -> ["red", "green", "orange", "yellow"]

results matching ""

    No results matching ""