What is the null type value in Javascript

Description

The null type has only one value: null. A null value is an empty object pointer. typeof returns "object" for null.

Example


var aString = null;
console.log(typeof aString);
console.log(typeof null);

The code above generates the following result.

Example 2

When defining a variable for an object, you should initialize the variable to null. In this way, you can check for null to determine if the variable has an object reference.


var car = null;
console.log(typeof car);   //"object"
if (car != null){/*from w ww.j  av a 2  s. co  m*/
    //do something with car
    console.log("car is not null");
}

The code above generates the following result.

null vs undefined

The value undefined is a derivative of null, so JavaScript defines them to be equal:


console.log(null == undefined);   

The code above generates the following result.

Using the equality operator (==) between null and undefined always returns true,

You should never explicitly set the value of a variable to undefined. But null should be used to initialize object variable.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions