The JavaScript Programming Language

null and undefined

Most programming languages have only one value for “no value” or “empty reference”. For example, that value is null in Java.

JavaScript has two of those special values: undefined and null.

 

null

null means 'no object' or 'no reference value'.

It is not equal to:

  • zero 0
  • empty string '' or ""
  • empty object {}

 

//null is an object 051null_comparison.js

console.log(typeof null); //object

 

null is not equal to empty string. null is not equal to zero.

console.log(Boolean('' == null)); //false
console.log(Boolean('' === null)); //false
console.log(Boolean(0 === null)); //false

 

Example: 051null_comparison.js

 

undefined

 In general undefined means 'no value'. The following cases will generate undefined value type:

  • variable without value (non initialized variable)
  • calling function without parameter
  • non existant object property

 

//non initialized variable
var x;
console.log(x); //undefined


//function without parameter
function fja(y) { return y; }
console.log(fja());


//non existent property
var obj = {prop1: 'Some string'};
console.log(obj.prop2);

 

Example: 053undefined_var.js

 

 

ReferenceError

When variable is not defined JS will show ReferenceError

console.log(x); // ReferenceError: x is not defined

Example: 054ReferenceError.js

 

 

Checking null value

To check does variable has a value you can use the following code:

 

 

if (v) {
        // v has a value
    } else {
        // v does not have a value
    }


if (v != null) {
        // v has a value
    } else {
        // v does not have a value
    }

 

if (v !== undefined && v !== null) {
        // v has a value
    } else {
        // v does not have a value
    }