5

When working within javascript can someone provide me a good reference or explanation over testing for equality/inequality and type coercion?

From what I have been reading I see where there are two principles of thought on using eqeq (==) vs. eqeqeq (===) some feel that you should not use eqeq and always as use eqeqeq as it is safer to use.

I have been playing around with some basic samples and I am having trouble discerning the difference or when best to use one over the other:

For example: here is some basic script I was writing out. When I test using eqeq or eqeqeq I get the same result. I have not seen an example yet where I would get a different results (ie. using eqeq returns true where eqeqeq returns false).

function write(message){

  document.getElementById('message').innerHTML += message +'<br/>';
}


var tim = { name: "tim" };
var tim2 = { name: "tim" };
//objects are equal to themselves ( == vs ==== eqeq or eqeqeq)
write("tim eq tim: " + (tim == tim)); //returns true

//objects are only equal to themselves regardless of containing value got that
write("tim eq tim2: " + (tim === tim2)); //returns false

//access the primative type to test true or false
write("tim value eq tim2 value: " + (tim.name === tim2.name)); //returns true
//how does this differ in efficency over the eqeq operator? is one safer to use over the other?
//write("tim value eq tim2 value: " + (tim.name == tim2.name)); //also returns true

//testing primatives

write("apple eqeqeq apple: " + ("apple" === "apple"));  //true
write("apple eqeqeq apple: " + ("apple" == "apple"));  //true

Can someone provide an explanation or reference I can read that helps clarify this a bit more.

cheers,

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
rlcrews
  • 3,482
  • 19
  • 66
  • 116

6 Answers6

3

The difference between == and === is fairly simple: == is a comparison of value. === is a comparison of value and type. Using === will prevent JavaScript from dynamically determining type and compares values exactly as they are.

5 == "5"     //true - JS compares the number 5 to a string of "5" and determines the contents are the same 
5 === "5"    //false - A character is not a number, they can't be the same.

0 == false   //true - false is a bool, 0 is numerical, but JS determines that 0 evaluates to false
0 === false  //false - numeric is not boolean, they can't be exactly the same thing

5 == 5.0     //true - need I say more?
5 === 5.0    //true - one is a float and one is an int, but JS treats them all as numerical

I find it's critical for tests with functions that can return both false (for failure) and 0 (as a legitimate result).

JS has a total of 5 primitive types = numerical, string, boolean, null and undefined. === requires both arguments to be of the same type and equal value to return true. There are no float, int, long, short, etc - any type of number is lumped together as numerical.

Surreal Dreams
  • 26,055
  • 3
  • 46
  • 61
1

Below is a very complete list of things that you won't expect when using equality operators

All of the following are true:

0               ==          ""
0               ==          " "
0               ==          []
false           ==          ""
false           ==          " "
false           ==          []
[]              ==          ""
null            ==          undefined
"str"           ==          ["str"]

"1"             ==          true
"0"             ==          false

"null"          !=          null
"false"         !=          false
"true"          !=          true
"undefined"     !=          undefined
"NaN"           !=          NaN

NaN             !=          NaN         //exception: NO exception
{}              !=          {}          //exception: same reference
[]              !=          []          //exception: same reference

--------------------------------------

new Number(10)      !==         10
new String("str")   !==         "str"
NaN                 !==         NaN     //exception: NO exception
{}                  !==         {}      //exception: same reference
[]                  !==         []      //exception: same reference

(Some of them came from this source)

In conclusion, never use ==. Not even when you want to:

"It is highly recommended to only use the strict equality operator. In cases where types need to be coerced, it should be done explicitly and not left to the language's complicated coercion rules."

(source)

ajax333221
  • 11,436
  • 16
  • 61
  • 95
1

It is simple.
== performs a type conversion and then compares converted values to your desired value
=== doesnt perform type conversion and directly compares your values.
Obviously === is better in terms of performance and accuracy but == is also convinient in some cases so you can use them both if they suit your needs.

comparisons

Cheers!

Boris D. Teoharov
  • 2,319
  • 4
  • 30
  • 49
0

=== is the strict equality operator which returns true only if the variables have the same type and value.

a = 1;
b = "1";

a == b will return true, a === b will return false

QuantumBlack
  • 1,549
  • 11
  • 27
0

The rule of == is not easy to remember, can you get all the right answer of below examples?

"" == "0" // false
0 == "" // true
0 == "0" // true
false == "false" // false
false == "0" // true
false == undefined // false
false == null // false
null == undefined // true
" \t\r\n" == 0 // true

So it is better only use ===, and never use ==.

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • the list is much bigger, I spend two hours today and found many more. `[] == ""`, `0 == " "`, `"1" == true`... etc. Also you should put the source http://bonsaiden.github.com/JavaScript-Garden/#types.equality – ajax333221 May 23 '12 at 02:59
  • These all make sense if you know C. Pointers are ints. Booleans are ints. Arrays are pointers. Strings are arrays. NULL is (was) 0. false is 0. Just saying. If you're curious, try figuring out what's up with this one: `[0] == false // => true` – superlukas Apr 24 '15 at 10:40
0

You must have heard someone that javascript is very loosely typed language.

So as surreal said above The (==) operator is used when you only want to compare the values of the arguments and do not care about their type like 5=="5" will return true. This is the case when you want to see (for instance what key the user pressed and you don't care about the the type of it may be a string, a char or an integer).

But there me be a case when the type of arguments also matters. In such cases you want to compare the types of the operators. So in those cases you use the triple equality operator. For example if you are performing some addition or multiplication operations then you want to make sure that the operands are of the compatible type. So you use the triple (===) operator.

me_digvijay
  • 5,374
  • 9
  • 46
  • 83