2

So I had en experiment I want to share here, because I didn't understand the reason why it happened and I can't find out a proper reason yet on SO or Google.

With the following code :

const cities = [
['p','a','r','i','s'],
['n','e','w',' ','y','o','r','k'],
['s','a','n',' ','f','r','a','n','c','i','s','c','o']
]

const citiesCopy = [...cities];

const citiesWithUppercase = 
citiesCopy
.map(city => {
  ['a', 's'].forEach((letter, i) => {
    city.includes(letter) && (city[city.indexOf(letter)] = letter.toUpperCase());
  })
  return city
})

console.log("cities", cities);

I expect the result of the console.log to be the original cities with lower case letters for a and s, as I am working only on a copy of cities, but actually they are upper case. Copy paste in your own console to see the result.

Can somebody explain why ?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
arnaudambro
  • 2,403
  • 3
  • 25
  • 51
  • Why do you think that? The nested arrays are the same in both arrays. – Ele May 17 '18 at 12:43
  • 1
    The copy of the `cities` array still contains the same arrays as `cities`. – Bergi May 17 '18 at 12:43
  • `citiesCopy` contains only references to the arrays from `cities`. It doesn't get the copies of those arrays. So you're modifying the same arrays. –  May 17 '18 at 12:44
  • Why the `reference`? – deEr. May 17 '18 at 12:47
  • "Why the reference" -- because that's how the spread works. It creates only a shallow copy -- meaning that if the original array contains an object, only a reference to that object will be copied to the new array. –  May 17 '18 at 12:49
  • @user234461 And why is that? Where does it say that in the `manual` MDN? – deEr. May 17 '18 at 12:56
  • @AjAX wrong username. – user234461 May 17 '18 at 12:59
  • @Bergi you are saying it's a duplicate question, but I looked for 15 minutes with my simple keywords and couldn't find the question you are targeting. Keywords speaking, maybe there is a problem with the other question. – arnaudambro May 17 '18 at 13:08
  • @arnaudambro Maybe because it uses the correct term, not "operator" – Bergi May 17 '18 at 13:17
  • Sorry, but the 'spread operator' expression is commonly used every where, even in MDN, even in the answer you point at – arnaudambro May 17 '18 at 13:24
  • Not being rude, but when I saw the question you point at in my results, I didn't think that my problem was anything to do with 'multidimensionnals array', because these words didn't ring any bell to me. They will from now on, we learn something everyday ! :) But this is to emphasize my point of keywords problem with that question, and why it didn't occur to me to click on it when I was doing my researches. – arnaudambro May 17 '18 at 13:28
  • I think also, that the explanation is still missing. – deEr. May 17 '18 at 14:42

0 Answers0