0

Can someone please explain why below statements alert 'Check passed' in javascript? Code is comparing a string object against an array, and I was expecting it to fail.

var someArray = ['Current'];

if('Current' == someArray){
   alert('Check passed');
}else{
   alert('Check failed');
}

It alerts 'Check passed'.

Atul P
  • 9
  • 2
    The `==` operator does all sorts of amazing things. When you compare something to a string, it converts the something to a string. As it happens, an array with that string in it like you have will be converted to just the string itself. – Pointy May 15 '15 at 05:04
  • My guess is it’s implicit type conversion. It’s probably a similar reason why `Number('42')` and `Number(['42'])` both return `42`. – Sebastian Simon May 15 '15 at 05:04
  • 1
    Unless you have a very good reason to, always use `===` in Javascript! – nathancahill May 15 '15 at 05:05
  • If you want to compare strictly use `===` comparator. – bish May 15 '15 at 05:05
  • Read _[this answer](http://stackoverflow.com/a/359509/3894168)_ – Zee May 15 '15 at 05:10

3 Answers3

1

When comparing with just == javascript tries to coerce the left and right values as the same types. In this case it tries to coerce them both to strings.

When arrays are coerced to strings(its toString function is called) each element of the array is joined together. In this case ["Current"] becomes "Current" so:

"Current" == someArray //becomes
"Current" == "Current" 

With multiple elements

["Current","Values"] would become "Current,Values"

If you do not want this to happen use the value and type compare operator ===

if("Current" === someArray){
   alert('Check passed');
}else{
   alert('Check failed');
}

Demo

var someArray = ["Current"];

if("Current" === someArray){
   alert('Check passed');
}else{
   alert('Check failed');
}
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
0

As mentioned in Which equals operator (== vs ===) should be used in JavaScript comparisons?

The == operator will compare for equality after doing any necessary type conversions.

Community
  • 1
  • 1
kwangsa
  • 1,701
  • 12
  • 16
0

The reason is implicit type conversion. The == operator doesn’t care about the type of two objects, as opposed to ===. But in order to compare two things of different type JavaScript first has to implicitly convert the Array to a String by calling Array.prototype.toString on that Array (whose result is identical to Array.prototype.join(',')).

(['Current']).toString();    // returns 'Current'
(['Current',42]).toString(); // returns 'Current,42'

therefore

(['Current',42]).toString() == 'Current,42'; // true

and then again

['Current',42] == 'Current,42'; // true
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75