Spread and Rest Operator

We use these operators many times. It's only one operator (...). 

Spread

    It is used to split up array elements OR object properties. As object and array in JS is copied by reference by default, so we use it to copy by value.
                            // [...oldArray] => will return all the values of old array in the form of array, but only value is assigned, not reference
    // [...oldArray, element1, element2] => will return all the elements of old array also element1 and element2 in the form of array

    const array = [2,5,6,2,1,345]

    // // Copy reference
    // const newArray = array;

    // Copy Values
    const newArray = [...array532,13];

    newArray.push(42,14);
    console.log(array);
    console.log(newArray);

    const obj = {  name: "Ayush" };

    // // Copy reference
    // const obj2 = obj;

    // Copy values
    const obj2 = {...objage: 21};

    obj2.game = "23";
    console.log(obj);
    console.log(obj2);

Rest

    It is used to merge a list of function arguments into an array, we can put here as many as agreement as we want, all the agreements will be treated as an array element here.
    function sortingFunction(...args) {
        return args.sort();
    }
    console.log(sortingFunction(1,3,6,43,2,4,56,7,65,43));
    
    It will print all the elements of the arguments in the form of a sorted array.

Comments