Is there a difference in the way cloning objects using the spread operator?

const a = { s:1, d:2 }; // этим способом const {...b} = a; // и этим способом const c = {...a}; 

    1 answer 1

    Judging by the tests, if it is necessary to clone an object "as is", there is no difference.

    However, if you need to remove, add or change something in the resulting object, then there is a difference.

    • If you need to clone the target object partially, then our choice is the first option:

       const first = { a:1, b:2, c:3, d:4 }; const { a, ...second } = first; console.log(second); // => { b:2, c:3, d:4 }; 
    • If you need to clone the target object and add or change some fields, then our choice is the second option:

      Add:

       const first = { a:1, b:2, c:3, d:4 }; const second = { ...first, e: 5}; console.log(second); // => { a:1, b:2, c:3, d:4, e:5 }; 

      Edit:

       const first = { a:1, b:2, c:3, d:4 }; const second = { ...first, d: 5}; console.log(second); // => { a:1, b:2, c:3, d:5 };