I am trying to understand how shallow copy works with map
and without map
on an array.
const arr = [
{
name: 'example',
inner: {
title: 'test'
}
}
]
const copy = arr.map(a => ({
...a
}))
copy[0].name = 'name1'
copy[0].inner.title = 'title1'
Updating name
prop on the copy
will not affect the original array arr
. However, updating inner.title
will modify both copy
and arr
. As far as I understand, in a shallow copy only top/first level props are copied, nested objects still share the same reference.
However, now if I create a shallow copy without using map
then even the first/top level props will share the same reference I think or at least updating first/top level props on the copy will affect the original one.
// same arr above
const copy2 = [...arr];
copy2[0].name = 'name2';
copy2[0].inner.title = 'title2';
Now, the original arr
's name
value is 'name2' and inner.title
value is 'title2'. Why is that? What is the exact difference between two code snippets, how map
plays a role in shallow copy?