Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Spread syntax modifies array #25976

Closed
mohitmayank opened this issue Feb 7, 2019 · 2 comments
Closed

Spread syntax modifies array #25976

mohitmayank opened this issue Feb 7, 2019 · 2 comments
Labels
invalid Issues and PRs that are invalid. question Issues that look for answers.

Comments

@mohitmayank
Copy link

mohitmayank commented Feb 7, 2019

const assert = require('assert'); 
 
const array = [ 
  {   
    id : 5 
  } ,
  {  
    id : 7 
  }   
]; 
 
const last = array.pop(); 
const obj = Object.assign(...array, last); 
// const obj = Object.assign(last, ...array); 
 
assert(array[0].id === 5);  //AssertionError
@mscdex
Copy link
Contributor

mscdex commented Feb 7, 2019

This is expected due to the following:

  • Object.assign() takes as its first argument the target object to assign properties to. All of the other arguments are source values/objects.
  • The spread syntax is equivalent to passing each value of the array to the function as separate arguments
  • Objects in javascript are passed/assigned by reference

With all of this in mind, the Object.assign() is equivalent to:

const obj = Object.assign(array[0], last);

So the properties of last are copied to array[0]. Since both have the same, single property, that means the value of 5 in array[0] is overwritten with the value of 7 from last.

@mscdex mscdex closed this as completed Feb 7, 2019
@mohitmayank
Copy link
Author

Er. Now when i look at your comment. it seems obvious. Thanks.

@ChALkeR ChALkeR added invalid Issues and PRs that are invalid. question Issues that look for answers. labels Feb 7, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
invalid Issues and PRs that are invalid. question Issues that look for answers.
Projects
None yet
Development

No branches or pull requests

3 participants