2

This is somewhat similar to split() in javascript, but here's my question, and it's more theoretical than practical

I have an array that looks like this:

var array = ["abc", "def"]

When I do

debug(array === array.toString().split(","));

I get false, I tried == and that also gives false. I did a debug dump of the array and the joined/split array and they look exactly the same in output. What is the difference between them that's causing this to evaluate to false?

I think it's pretty clear for my code that I can just use array without having to do toString.split (it was necessary earlier, I think, not anymore), I'm just curious as to what's going on here.

1
  • use array.slice() instead of array.toString().split(",") when needed... Commented Apr 8, 2014 at 16:49

5 Answers 5

5

Because array.toString().split(",") returns a new instance of the array. Arrays, being objects, are only equal if they are the exact same instance of the array:

var a = [1,2];
var b = [1,2];
var c = a;
alert(a == c); // true
alert(a == b); // false - not even loose comparison can save you
Sign up to request clarification or add additional context in comments.

Comments

5

Neither the == nor the === operator will inspect the contents of an array. Rather, they test whether the two operands reference the same array instance in memory. Notice:

['a', 'b'] === ['a', 'b']; // false

var arr = ['a', 'b'];
arr === arr;               // true

In other words, when you're comparing two different arrays, == or === will always return false;

Comments

1

Quoting from the MDN Doc for Comparison Operators,

Note that an object is converted into a primitive if, and only if, its comparand is a primitive. If both operands are objects, they're compared as objects, and the equality test is true only if both refer the same object.

So, if we compare any two objects, then both == and === will check if they are one and the same. You can check that like this

console.log({} == {});
# false
console.log({} === {});
# false
console.log([] == []);
# false
console.log([] === []);
# false

I believe the reason could be, Arrays and Objects can be nested and it will be very difficult to check if two objects are equal.

Comments

0

The == and === operators do not compare the contents of Arrays. They just check to see if the two Arrays are actually the same Array object.

Comments

0

Array is not a primitive type, they are not the same reference.

var a = ["a"];
var b = ["a"];
console.log(a == b); //false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.