1

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

Nouman Javed
  • 129
  • 1
  • 1
  • 13

2 Answers2

3

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.

Hari Reddy
  • 339
  • 3
  • 15
vszholobov
  • 2,133
  • 1
  • 8
  • 23
0

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?

Hari Reddy
  • 339
  • 3
  • 15