1

var hits = ["a", "b", "c"];

if (hits !== ["a", "b", "c"]){
//Do some stuff here
};

Can you use the value of an array as a comparsion? The above does not seem to work for me I was wondering if this is the way to go about it or if there is another way to access the literal value of an array for comparison.

3 Answers3

5

The equality operators (=== and !==) compare references, not values in case of objects. Mind that in JavaScript Arrays are objects. Because of that and because these are two distinct arrays (they look the same, they contain the same values, but they're not the same array) their references differ:

If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

You can read more about it on MDN.

Note: == and != equality operators also compare objects by references, but since they do more than just simple comparison (and it's often unexpected), it's generally advised not to use them and always stick to strict equality operators (=== and !==).

How to compare arrays then?

There are at least a few different methods. Some people advise to compare JSON.stringify of both arrays but, even though it works for simple cases, it's not really a good solution performance-wise. You can find better methods here https://stackoverflow.com/a/14853974/704894

If you happen to use some kind of utility library such as lodash or underscore this function is already there! See https://lodash.com/docs#isEqual

Community
  • 1
  • 1
Michał Miszczyszyn
  • 11,835
  • 2
  • 35
  • 53
0

You can write this

if (JSON.stringify(hits) === JSON.stringify(["a", "b", "c"])) {
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can't do it this way because of the way Javascript handles arrays - it's not checking the values are the same, it's checking that the object is the same object (which it isn't).

millerbr
  • 2,951
  • 1
  • 14
  • 25
  • This is actually not a good idea. What if you had something like this in an array? `['a,b', 'b', 'c']` and in a second one something like this: `['a', 'b,b', 'c']`? It would return `true`, but those are not same arrays. – Paulooze Mar 24 '16 at 13:58
  • 1
    Hmm, yes of course - I will remove the suggested code – millerbr Mar 24 '16 at 14:01