2

What is the difference between next if statements in javascript when checking with null?

var a = "";
if( a != null ) // one equality sign
    ....
if( a !== null ) // two equality sign
   ....

When comparing to null I can't find any difference.

broadband
  • 3,266
  • 6
  • 43
  • 73

6 Answers6

0

In JavaScript, null has type: object (try yourself executing the following sentence typeof null).

That is, !== will check that a is also object before checking if the reference equals.

Actually you know that === and !== are meant to check that both left and right side of the equality have the same type without implicit conversions involved. For example:

"0" == 0 // true
"0" === 0 // false

Same reasoning works on null checking.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
0

According to http://www.w3schools.com/js/js_comparisons.asp

!=  - not equal
!== - not equal value or not equal type
suvroc
  • 3,058
  • 1
  • 15
  • 29
0

!= checks

negative equality

while !== checks for

negative identity

For example,

var a = "";

a != false; //returns false since "" is equal false
a !== false; //returns true since "" is not same as false

but if you are comparing it with null, then value will be true in both ocassion since "" is neither equal nor identical to null

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

There is no difference between them when comparing to null.

When we use strict equality (!==) it is obvious because they have different types, but when we use loose equality (!=) it is an important thing to remember about JavaScript language design.

Because of language design there are also some common questions:

Community
  • 1
  • 1
aeryaguzov
  • 1,143
  • 1
  • 10
  • 21
0
var a = "";
(1) if( a != null ) // one equality sign

Above condition(1) checks value only and not data-type, this will return true.

    ....
(2) if( a !== null ) // two equality sign

This checks value and data-type both, this will true as well.

To understand it more precisely,

var a = "1";

if( a == 1) {
    alert("works and doesn't check data type string");
}


if( a === 1) {
    alert('doesn't works because "1" is string');
}

if( a === "1") {
    alert('works because "1" is string');
}
Alpesh Panchal
  • 1,723
  • 12
  • 9
0

There is a difference if variable has value undefined:

var a = undefined;

if( a != null ) // doesn't pass
  console.log("ok");

if( a !== null ) // passes
  console.log("ok");

Got idea from reading this great post Why ==null, Not ===null. Also != is faster.

broadband
  • 3,266
  • 6
  • 43
  • 73