[javascript] JavaScript checking for null vs. undefined and difference between == and ===

  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 "===" )?

This question is related to javascript null undefined

The answer is


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:


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

_x000D_
_x000D_
let x;      // undefined_x000D_
let y=null; // null_x000D_
let z=3;    // has value_x000D_
// 'w'      // is undeclared_x000D_
_x000D_
if(!x) console.log('x is null or undefined');_x000D_
if(!y) console.log('y is null or undefined');_x000D_
if(!z) console.log('z is null or undefined');_x000D_
_x000D_
try { if(w) 0 } catch(e) { console.log('w is undeclared') }_x000D_
// typeof not throw exception for undelared variabels_x000D_
if(typeof w === 'undefined') console.log('w is undefined');
_x000D_
_x000D_
_x000D_

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


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

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

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 .


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


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);
}

}


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to null

getElementById in React Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? How to resolve TypeError: Cannot convert undefined or null to object Check if returned value is not null and if so assign it, in one line, with one method call How do I assign a null value to a variable in PowerShell? Using COALESCE to handle NULL values in PostgreSQL How to check a Long for null in java Check if AJAX response data is empty/blank/null/undefined/0 Best way to check for "empty or null value"

Examples related to undefined

Checking for Undefined In React Raw_Input() Is Not Defined How to resolve TypeError: Cannot convert undefined or null to object "undefined" function declared in another file? Passing Variable through JavaScript from one html page to another page Javascript - removing undefined fields from an object PHP How to fix Notice: Undefined variable: Undefined Symbols for architecture x86_64: Compiling problems Undefined or null for AngularJS PHP Notice: Undefined offset: 1 with array when reading data