Loading...

Spread & Rest in JavaScript

The spread operator allows for an object's properties to be filled into a another object right in line with existing properties. Likewise, this can fill one array's values in another array while keeping them in line with existing values.

Spread

const aNewObject = {...oldObject}
const aNewArray = [...oldArray]

Rest

The rest parameter an array made out of an infinite number of values. One use is to grab all arguments passed to a function that are not defined.

function myFun(argOne, argTwo, ...theRestOfThem) {
 console.log("argOne", argOne)
 console.log("argTwo", argTwo)
 console.log("theRestOfThem", theRestOfThem)
}

Another use is to grab the remaining items after destructuring . This will work for both objects and arrays. You can find more detail on what destructuring is here →

const {
    propName1,
    propName2,
    ...restOfOldObject
} = oldObject;

[first, second, ...others] = anArray

↓ Examples ↓

//    Set the Object
const animals = {
    tiger: 23,
    lion: 5,
    monkey: 2
}


//    Spread one Object into another
const aNewObject = {
    ...animals
}
console.log(aNewObject); //    RESULT: {tiger: 23, lion: 5, monkey: 2}


//    Add items while adding the original object
const aNewObject2 = {
    donkey: 3,
    ...animals,
    horse: 2
}
console.log(aNewObject2); //    RESULT: {donkey: 3, tiger: 23, lion: 5, monkey: 2, horse: 2}


// Spread one array into another
const firstNumbers = [1, 2, 3];
const thirdNumbers = [7, 8, 9];
const theGroup = [...firstNumbers, 4, 5, 6, ...thirdNumbers];

console.log(theGroup ); //=> [1, 2, 3, 4, 5, 6, 7, 8, 9]


// Spread into a function's arguments
const = array = [1, 2, 3, 4, 5];

function sum(a, b, c, d, e) {
    return a + b + c + d + e;
}

sum(...array); //    RESULT: 15


// Use destructuring to grab what you want and hold the rest in a new object
const {
    tiger,
    ...theOthers
} = animals;
console.log(tiger); //    RESULT: 23
console.log(theOthers) //    RESULT: {lion: 5, monkey: 2}


//    More destructuring
const {
    lion,
    ...someMore
} = animals;
console.log(lion); //    RESULT: 23
console.log(someMore) //    RESULT: {tiger: 23, monkey: 2}


//    Destructure an object and then spread into a function's parameters
function objectSpread(p1, p2) {
    console.log(p1);
    console.log(p2);
}

const {
    monkey,
    ...theRest
} = animals;
objectSpread(monkey, theRest); //    RESULT: 2 {tiger: 23, lion: 5}

One Reply to “Spread & Rest in JavaScript”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

q
↑ Back to Top