Let's say I have an array of names as let names = ['alex', 'mike']
and I make a copy of it using let namesCopy = names.slice()
Now names == namesCopy
returns false. I don't understand why
Let's say I have an array of names as let names = ['alex', 'mike']
and I make a copy of it using let namesCopy = names.slice()
Now names == namesCopy
returns false. I don't understand why
Because ==
compares links to array objects, not arrays themselves. The slice()
method creates a copy of the array. If you try to compare an array element by element, you will get true
.
Also, check this question.
The Slice function does not modify the array. By definition, the slice()
method returns a shallow copy of a portion of an array into a new array object.
slice()
copies object references into the new array. This new array object is a reference to the original array or a part of it. Both arrays refer to the same object and if it changes, the changes are visible to both the new and original arrays.
Here's a fun little example -
let cristiano = { country: 'portugal', club: 'real madrid'}
let messi = { country: 'argentina', club: 'barcelona' }
let players = [cristiano, messi]
let playersClone = players.slice()
cristiano.club = "juventus"
console.log(players[0].club)
// Output - "juventus"
console.log(playersClone[0].club)
// Output - "juventus"
Similarly, since the reference can't equal the value, names == namesCopy
returns false
.
Conclusion - JavaScript can be cool but weird just as much?