-3

This appears as a very basic question, but couldn't find any explanations on SO.

Consider this:

var arr = [1, 2, 3];
var str = "123";

function compare(){
  return arr.join('').split('') === str.split('')
}

console.log(compare());
console.log(arr.join('').split(''))
console.log(str.split(''))

Cant understand why console logs false...?

buzz
  • 9
  • 3

3 Answers3

4

Because although the two arrays you're comparing are equivalent, they are not the same array. == (and ===) with objects checks to see if they're the same object.

What you have, in effect, is:

console.log(["1", "2", "3"] == ["1", "2", "3"]);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Oh, right, the references are different. Now I get it. It wasn't my fault - my brain's sensory neurons did that – buzz Apr 19 '18 at 07:41
2

You compare two objects' references, not their content. Because you have 2 different objects, their references are not equal.

=== with reference types will return true if 2 variables refer to the same object. In the below example both a and b refer to the same object (same part in the memory), so they are equal.

const a = {};
const b = a; // assign `a`'s value, which is a reference to the `b`

console.log(a === b);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

They are not same array & they are separate object reference. If you want to compare these two , then stringify them

var arr = [1, 2, 3];
var str = "123";

function compare() {
  return (arr.join('').split('')).toString() === str.split('').toString()
}

console.log(compare());
console.log(arr.join('').split(''))
console.log(str.split(''))
brk
  • 48,835
  • 10
  • 56
  • 78