595
  1. How do I check a variable if it's null or undefined and what is the difference between the null and undefined?

  2. What is the difference between == and === (it's hard to search Google for "===" )?

Chei
  • 1,965
  • 3
  • 18
  • 28
MUG4N
  • 18,011
  • 10
  • 52
  • 81
  • 10
    2. The difference between `==` and `===` is well [described here](http://jquery-howto.blogspot.com/2012/11/jquery-double-tripple-equal-difference.html). – Uzbekjon Feb 14 '13 at 09:37
  • 1. Use === Instead of == JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing. "If two operands are of the same type and value, then === produces true and !== produces false." - JavaScript: The Good Parts However, when working with == and !=, you'll run into issues when working with different types. In these cases, they'll try to coerce the values, unsuccessfully. http://code.tutsplus.com/tutorials/24-javascript-best-practices-for-beginners--net-5399 – jasonleonhard Dec 19 '14 at 20:23
  • 4
    You can search Google for: "strict equality operator" - that fetches very relevant results – Danield Nov 17 '15 at 10:41
  • Just to add to the many answers here that you can use https://lodash.com/docs#isNil function to check if variable is null or undefined – Kfir Erez Jun 15 '16 at 08:03

8 Answers8

951

How do I check a variable if it's null or undefined...

Is the variable null:

if (a === null)
// or
if (a == null) // but see note below

...but note the latter will also be true if a is undefined.

Is it undefined:

if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below

...but again, note that the last one is vague; it will also be true if a is null.

Now, despite the above, the usual way to check for those is to use the fact that they're falsey:

if (!a) {
    // `a` is falsey, which includes `undefined` and `null`
    // (and `""`, and `0`, and `NaN`, and [of course] `false`)
}

This is defined by ToBoolean in the spec.

...and what is the difference between the null and undefined?

They're both values usually used to indicate the absence of something. undefined is the more generic one, used as the default value of variables until they're assigned some other value, as the value of function arguments that weren't provided when the function was called, and as the value you get when you ask an object for a property it doesn't have. But it can also be explicitly used in all of those situations. (There's a difference between an object not having a property, and having the property with the value undefined; there's a difference between calling a function with the value undefined for an argument, and leaving that argument off entirely.)

null is slightly more specific than undefined: It's a blank object reference. JavaScript is loosely typed, of course, but not all of the things JavaScript interacts with are loosely typed. If an API like the DOM in browsers needs an object reference that's blank, we use null, not undefined. And similarly, the DOM's getElementById operation returns an object reference — either a valid one (if it found the DOM element), or null (if it didn't).

Interestingly (or not), they're their own types. Which is to say, null is the only value in the Null type, and undefined is the only value in the Undefined type.

What is the difference between "==" and "==="

The only difference between them is that == will do type coercion to try to get the values to match, and === won't. So for instance "1" == 1 is true, because "1" coerces to 1. But "1" === 1 is false, because the types don't match. ("1" !== 1 is true.) The first (real) step of === is "Are the types of the operands the same?" and if the answer is "no", the result is false. If the types are the same, it does exactly what == does.

Type coercion uses quite complex rules and can have surprising results (for instance, "" == 0 is true).

More in the spec:

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • 126
    To distill TJ's answer, === means value AND type are the same. – Slappy Feb 24 '11 at 08:48
  • can I also use a the other way around like: if (a){} which would mean is not null or undefined right? – MUG4N Feb 24 '11 at 09:16
  • 13
    @Slappy: :-) @MUG4N: Yes, that's right. `if (a) { ... }` would mean "if `a` is truthy," where "truthy" is a non-zero, non-null, non-undefined, non-false, non-empty-string value. :-) – T.J. Crowder Feb 24 '11 at 10:10
  • A slight correction to the above, `if(a == null)` checks to see if `a` is `null` **or** `undefined`. As written above, it implies `a == null` ensures the variable is `null`. To ensure the variable is `null`, use `===`. – Nathan Wall Oct 04 '12 at 02:54
  • @NathanWall: Thanks, I was surprised to see that text in an answer of mine, but there's no sign that someone else edited it. Odd. I've clarified things. – T.J. Crowder Oct 04 '12 at 07:18
  • As to null being an object, I read once an article by Douglas Crockford in which he says that though typeof null returns 'object', null is really not an object. He says that this was an error introduced in javascript v.1 and reverse engineered by Microsoft into JScript. When Javascript was standardized by ECMA, this error was left intentionally, because it would introduce large problems with backward compatibility of old scripts. – zszep Sep 21 '13 at 07:00
  • 2
    @Željko: I think Crockford may be mistaken on this point. It's true that `null` isn't an *object*, it's an object reference meaning "no object". This is important, because it's what's used with host-provided interfaces when they provide object references but don't have one to provide (e.g., `node.nextSibling` when `node` is the last element in its parent, or `getElementById` when there's no element with that ID). The technology the host uses for this may not be as flexible as JavaScript is about variable/property types, so it was necessary to have a `null` obj ref (as opposed to `undefined`). – T.J. Crowder Sep 21 '13 at 09:55
  • 2
    I have to agree that Crockford is mistaken. `typeof null` returning "object" makes sense. The only other value that would make sense would be "null", since it definitely should return something different from `typeof undefined`. null represents a null object reference, which, at the very least, means the variable holding it is meant for some type of 'object'. If it was a mistake, it was a good mistake. Anyway, in regards to the answer, the tip about `undefined` !== `undefined` during cross-window scripting is good to know, especially for debugging purposes. – Triynko May 08 '14 at 15:07
  • There is no problem with undefined when doing cross-window scripting. While it is true that with multiple windows you will have multiple variables named `undefined`, the `===` operator does not compare variables, it compares values, and both of these variables will hold the primitive `undefined` value, and you can compare these just fine. – Rene Saarsoo Jul 06 '14 at 10:09
  • @ReneSaarsoo: Back in 2005 or so I recall being told by one of the PrototypeJS devs that there were some browsers where there was an issue, where the actual *value* differed (not that `undefined` had been redefined). This would, of course, be a bug in the relevant browser. I've just checked various modern browsers, and also IE6 and Firefox 3.6 (yes, really), and none of them have that problem, `===` works as expected. If it really was an issue, I don't know what browser it was an issue with, and I expect it's archaic. I've removed that bit as being outdated or wrong. – T.J. Crowder Jul 06 '14 at 12:12
  • Great answer. This elegantly clears why the recommended assignment with a fallback default value looks like this: `value = checkedValue || defaultValue;` I've seen this being recommended in the AngularJS tutorial, but this answer thoroughly explains the background :) – dk1844 Dec 23 '15 at 09:21
  • Don't forget that `undefined` is not a language keyword. That means that `if (a == undefined)` is basically comparing `a` to a global variable called `undefined` which you're assuming hasn't been defined. Someone accidentally or maliciously creating a global variable called `undefined` can change the meaning of your code out from under you. Taking advantage of falsy comparison with `if (a)` is probably safer as long as you don't care about the distinction between null and undefined in your use case. – Joel Mueller Sep 07 '16 at 00:36
  • 1
    If `if (a == null)` would return true if a is `undefined`, is it therefore safe to check only `a == null` if I want to check if a is either `null` or `undefined`? – Rodders Sep 07 '16 at 08:19
  • @Rodders: Yes. I used to be bothered by doing that because it's a bit misleading, but at this point, I think it's coming into "idiom" status. :-) – T.J. Crowder Sep 07 '16 at 09:22
  • @T.J.Crowder Thanks for your detailed answer. One part I can't figure out though is your mention that "there's a difference between calling a function with the value undefined for an argument, and leaving that argument off entirely." What is the difference? – sabliao Sep 27 '16 at 06:35
  • 1
    @sabliao: The number of arguments the function receives. If you call `foo(undefined)`, `foo` receives 1 argument with the value `undefined`. If you call `foo()`, `foo` receives no arguments at all. (If it declares an argument, though, that argument's value will be `undefined` in both cases. But you can tell the difference if you use ES2015's rest arguments or the ES5 and earlier `arguments` pseudo-array.) – T.J. Crowder Sep 27 '16 at 06:39
  • you have the sub-code comment for the undefined and null switched up. – saalehr Oct 28 '16 at 03:16
  • @saalehr: If you mean the two comments just under code blocks near the beginning of the answer starting with *"...but"* then no, they aren't switched up. – T.J. Crowder Oct 28 '16 at 05:31
  • Great explanation. I would like to add that there are circumstances where typeof variable === "undefined" would be very much preferable to variable === undefined. This is when you are accessing a variable, that may not be declared. typeof variable === "undefined" would work correctly in such circumstances whereas variable === undefined would throw an error. https://stackoverflow.com/a/4725697/3154611 – Gopal Krishnan Feb 21 '18 at 10:09
97

The difference is subtle.

In JavaScript an undefined variable is a variable that as never been declared, or never assigned a value. Let's say you declare var a; for instance, then a will be undefined, because it was never assigned any value.

But if you then assign a = null; then a will now be null. In JavaScript null is an object (try typeof null in a JavaScript console if you don't believe me), which means that null is a value (in fact even undefined is a value).

Example:

var a;
typeof a;     # => "undefined"

a = null;
typeof null;  # => "object"

This can prove useful in function arguments. You may want to have a default value, but consider null to be acceptable. In which case you may do:

function doSomething(first, second, optional) {
    if (typeof optional === "undefined") {
        optional = "three";
    }
    // do something
}

If you omit the optional parameter doSomething(1, 2) thenoptional will be the "three" string but if you pass doSomething(1, 2, null) then optional will be null.

As for the equal == and strictly equal === comparators, the first one is weakly type, while strictly equal also checks for the type of values. That means that 0 == "0" will return true; while 0 === "0" will return false, because a number is not a string.

You may use those operators to check between undefined an null. For example:

null === null            # => true
undefined === undefined  # => true
undefined === null       # => false
undefined == null        # => true

The last case is interesting, because it allows you to check if a variable is either undefined or null and nothing else:

function test(val) {
    return val == null;
}
test(null);       # => true
test(undefined);  # => true
Julien Portalier
  • 2,791
  • 18
  • 22
  • 1
    Kyle Simpson claims typeof null returning "object" is a bug: https://github.com/getify/You-Dont-Know-JS/blob/master/up%20&%20going/ch2.md#values--types – bzrk Dec 14 '15 at 15:53
17

The spec is the place to go for full answers to these questions. Here's a summary:

  1. For a variable x, you can:

    • check whether it's null by direct comparison using ===. Example: x === null
    • check whether it's undefined by either of two basic methods: direct comparison with undefined or typeof. For various reasons, I prefer typeof x === "undefined".
    • check whether it's one of null and undefined by using == and relying on the slightly arcane type coercion rules that mean x == null does exactly what you want.

  2. The basic difference between == and === is that if the operands are of different types, === will always return false while == will convert one or both operands into the same type using rules that lead to some slightly unintuitive behaviour. If the operands are of the same type (e.g. both are strings, such as in the typeof comparison above), == and === will behave exactly the same.

More reading:

Community
  • 1
  • 1
Tim Down
  • 292,637
  • 67
  • 429
  • 506
12

How do I check a variable if it's null or undefined

just check if a variable has a valid value like this :

if(variable)

it will return true if variable does't contain :

  • null
  • undefined
  • 0
  • false
  • "" (an empty string)
  • NaN
Sumit Joshi
  • 922
  • 1
  • 12
  • 21
8

undefined

It means the variable is not yet intialized .

Example :

var x;
if(x){ //you can check like this
   //code.
}

equals(==)

It only check value is equals not datatype .

Example :

var x = true;
var y = new Boolean(true);
x == y ; //returns true

Because it checks only value .

Strict Equals(===)

Checks the value and datatype should be same .

Example :

var x = true;
var y = new Boolean(true);
x===y; //returns false.

Because it checks the datatype x is a primitive type and y is a boolean object .

kannanrbk
  • 5,894
  • 11
  • 46
  • 84
5

Ad 1. null is not an identifier for a property of the global object, like undefined can be

let x;      // undefined
let y=null; // null
let z=3;    // has value
// 'w'      // is undeclared

if(!x) console.log('x is null or undefined');
if(!y) console.log('y is null or undefined');
if(!z) console.log('z is null or undefined');

try { if(w) 0 } catch(e) { console.log('w is undeclared') }
// typeof not throw exception for undelared variabels
if(typeof w === 'undefined') console.log('w is undefined');

Ad 2. The === check values and types. The == dont require same types and made implicit conversion before comparison (using .valueOf() and .toString()). Here you have all (src):

if

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
1

If your (logical) check is for a negation (!) and you want to capture both JS null and undefined (as different Browsers will give you different results) you would use the less restrictive comparison: e.g.:

var ItemID = Item.get_id();
if (ItemID != null)
{
 //do stuff
}

This will capture both null and undefined

Homer
  • 7,084
  • 13
  • 66
  • 104
DaniDev
  • 2,060
  • 19
  • 28
0

Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.

function myFunction() {
var data;  //The Values can be like as null, blank, undefined, zero you can test

if(!(!(data)))
{
   //If data has valid value
    alert("data "+data);
} 
else 
{
    //If data has null, blank, undefined, zero etc.
    alert("data is "+data);
}

}

Ravikant
  • 79
  • 5