Ads Top

What is spread operator?

Spread Operator in Javascript: Spread operator is the advance javascript feature that gives a flexibility adding more array and objects. If we use three dots(…) in the any object or array then this is indicate that we are merging another array. Also Rest operator using three dots (…).

Where we need merge one array or more array then simply use( …) three dots before array name. If you will not use three dots then you will found your whole array show as it is. But when using with three dots then we will get value as merged array. As below example:

// without spread operator

    const arr = [1'name'3];

    const arrNew = [arr, 45];

    console.log(arrNew); // [Array(3), 4, 5]

 

    // with spread operator

    const arr1 = [1'name'3];

    const arrNew1 = [...arr1, 45];

    console.log(arrNew1); // [1, "name", 3, 4, 5]

Also we can use spread operator between array. Spread operator example below:

    const firstArray = [123];

    const secondArray = [...firstArray, 45];

    console.log(secondArray); // [1, 2, 3, 4, 5]

 

    const thirdArray = [123];

    const fourthArray = [45, ...thirdArray];

    console.log(fourthArray); // [4, 5, 1, 2, 3]

 

    const fiftthArray = ["Sheo"5, ...fourthArray, 'Sagar', ...firstArray];

    console.log(fiftthArray); // ["Sheo", 5, 4, 5, 1, 2, 3, "Sagar", 1, 2, 3]

We are using spread operator for the object. Spread operator example for the object:

 // without spread operator

    const obj = {

        firstName: 'Sheo'

    };

    const objNew = {

        obj,

        lastName: 'Sagar'

    };

    console.log(objNew); // {obj: {…}, lastName: "Sagar"}

 

    // with spread operator

    const obj1 = {

        firstName: 'Sheo'

    };

    const obj2 = {

        ...obj1,

        lastName: 'Sagar'

    };

    console.log(obj2); // {firstName: "Sheo", lastName: "Sagar"}

 

    const firstObj = {

        fname: 'Sheo',

        mob : '965233'

    };

    const secondObj = {

        ...firstObj,

        lname: 'sagar',

    };

    console.log(secondObj); // {fname: "Sheo", mob: "965233", lname: "sagar"}

 

    const thirdObj = {

        fname: 'Sheo',

        mob : '965233'

    };

    const fourthObj = {

        lname: 'sagar',

        ...thirdObj,

    };

    console.log(fourthObj); // {lname: "sagar", fname: "Sheo", mob: "965233"}

 

    const fiftthObj = {

        fname: 'Raj',

        mob : '93156',

        ...secondObj,

        lname: 'sagar',

        ...thirdObj,

    };

    console.log(fiftthObj); // {fname: "Sheo", mob: "965233", lname: "sagar"}

    // because same property replaced if you will change new 

property then it reflect 

 

No comments:

Copyright Reserved to Anything Learn. Powered by Blogger.