What is the difference between null and undefined in JavaScript?

I want to know what the difference is between null and undefined in JavaScript.

In JavaScript, undefined means a variable has been declared but has not yet been assigned a value, such as:

var TestVar;
alert(TestVar); //shows undefined
alert(typeof TestVar); //shows undefined

null is an assignment value. It can be assigned to a variable as a representation of no value:

var TestVar = null;
alert(TestVar); //shows null
alert(typeof TestVar); //shows object

From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

null === undefined // false
null == undefined // true
null === null // true


null = 'value' // ReferenceError
undefined = 'value' // 'value'

I picked this from here

The undefined value is a primitive value used when a variable has not been assigned a value.

The null value is a primitive value that represents the null, empty, or non-existent reference.

When you declare a variable through var and do not give it a value, it will have the value undefined. By itself, if you try to WScript.Echo() or alert() this value, you won't see anything. However, if you append a blank string to it then suddenly it'll appear:

var s;
WScript.Echo("" + s);

You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". This is a small difference indeed.

You can even compare a variable that is undefined to null or vice versa, and the condition will be true:

undefined == null
null == undefined

They are, however, considered to be two different types. While undefined is a type all to itself, null is considered to be a special object value. You can see this by using typeof() which returns a string representing the general type of a variable:

var a;
var b = null;

Running the above script will result in the following output:


Regardless of their being different types, they will still act the same if you try to access a member of either one, e.g. that is to say they will throw an exception. With WSH you will see the dreaded "'varname' is null or not an object" and that's if you're lucky (but that's a topic for another article).

You can explicitely set a variable to be undefined, but I highly advise against it. I recommend only setting variables to null and leave undefined the value for things you forgot to set. At the same time, I really encourage you to always set every variable. JavaScript has a scope chain different than that of C-style languages, easily confusing even veteran programmers, and setting variables to null is the best way to prevent bugs based on it.

Another instance where you will see undefined pop up is when using the delete operator. Those of us from a C-world might incorrectly interpret this as destroying an object, but it is not so. What this operation does is remove a subscript from an Array or a member from an Object. For Arrays it does not effect the length, but rather that subscript is now considered undefined.

var a = [ 'a', 'b', 'c' ];
delete a[1];
for (var i = 0; i < a.length; i++)
WScript.Echo((i+".) "+a[i]);

The result of the above script is:

0.) a
1.) undefined
2.) c

You will also get undefined returned when reading a subscript or member that never existed.

The difference between null and undefined is: JavaScript will never set anything to null, that's usually what we do. While we can set variables to undefined, we prefer null because it's not something that is ever done for us. When you're debugging this means that anything set to null is of your own doing and not JavaScript. Beyond that, these two special values are nearly equivalent.

This is the difference

(adding characters due to lack of characters, so I'm allowed to post this.)

null is a special keyword that indicates an absence of value.

think about it as a value, like:

  • "foo" is string,
  • true is boolean ,
  • 1234 is number,
  • null is undefined.

undefined property indicates that a variable has not been assigned a value including null too . Like

var foo;

defined empty variable is null of datatype undefined

Both of them are representing a value of a variable with no value

AND null doesn't represent a string that has no value - empty string-


var a = ''; 
console.log(typeof a); // string 
console.log(a == null); //false 
console.log(a == undefined); // false 

Now if

var a;
console.log(a == null); //true
console.log(a == undefined); //true 


var a; 
console.log(a === null); //false 
console.log(a === undefined); // true

SO each one has it own way to use

undefined use it to compare the variable data type

null use it to empty a value of a variable

var a = 'javascript';
a = null ; // will change the type of variable "a" from string to object 

null: absence of value for a variable; undefined: absence of variable itself;

..where variable is a symbolic name associated with a value.

JS could be kind enough to implicitly init newly declared variables with null, but it does not.

Please read the following carefully. It shall remove all your doubts regarding the the difference between null and undefined in JavaScript. Also you can use the utility function given below to exactly determine types.

In JavaScript we can have following types of variables.

  1. Undeclared Variables
  2. Declared but Unassigned Variables
  3. Variables assigned with literal undefined
  4. Variables assigned with literal null
  5. Variables assigned with anything other than undefined or null

Following explains each of these cases one by one

  1. Undeclared Variables: Following holds true for undeclared variables

    • Can only be checked by typeof() which returns string 'undefined'
    • Cannot be checked with == or === or by if or conditional operator ? (throws Reference Error)
  2. Declared but Unassigned Variables

    • typeof returns string 'undefined'
    • == check with null returns true
    • == check with undefined returns true
    • === check with null returns false
    • === check with undefined returns true
    • if or conditional operator ? returns false
  3. Variables assigned with literal undefined: These variables are treated similarly as the Declared But Unassigned Variables.

  4. Variables assigned with literal null

    • typeof returns string 'object'
    • == check with null returns true
    • == check with undefined returns true
    • === check with null returns true
    • === check with undefined returns false
    • if or conditional operator ? returns false
  5. Variables assigned with anything other than undefined or null

    • typeof returns one of the following strings: 'string','number','boolean','function', 'object','symbol'

Following provides the algorithm for correct type checking of a variable:

  1. Check for undeclared/unassigned/assigned with undefined using typeof. return if string 'undefined' is returned.
  2. Check for null using ===. return 'null' if true.
  3. Check for actual type using typeof. return type if not equal to 'object'
  4. Call Object.prototype.toString.call(o) to determine actual object type. It shall return a string of type '[object ObjectType]' for all the built in Javascript or DOM defined Objects. For user defined objects it returns '[object Object]'

You can also use the following utility function for determining types. It currently supports all ECMA 262 2017 types.

function TypeOf(o,bReturnConstructor)
   if(typeof o==='undefined') return 'undefined'
   if(o===null) return 'null'   
   if(typeof o!=='object') return typeof o

   var type=Object.prototype.toString.call(o)
     //Value types:4
     case '[object Number]': type='number';break;
     case '[object String]': type='string';break;
     case '[object Boolean]': type='boolean';break;
     case '[object Date]': type='date';break;

   //Error Types:7
     case '[object Error]': type='error';break;
     case '[object EvalError]': type='evalerror';break;
     case '[object RangeError]': type='rangeerror';break;
     case '[object ReferenceError]': type='referenceerror';break;
     case '[object SyntaxError]': type='syntaxerror';break;
     case '[object TypeError]': type='typeerror';break;
     case '[object URIError]': type='urierror';break;

    //Indexed Collection and Helper Types:13
     case '[object Array]': type='array';break;
     case '[object Int8Array]': type='int8array';break;
     case '[object Uint8Array]': type='uint8array';break;
     case '[object Uint8ClampedArray]': type='uint8clampedarray';break;
     case '[object Int16Array]': type='int16array';break;
     case '[object Uint16Array]': type='uint16array';break;
     case '[object Int32Array]': type='int32array';break;
     case '[object Uint32Array]': type='uint32array';break;
     case '[object Float32Array]': type='float32array';break;
     case '[object Float64Array]': type='float64array';break;
     case '[object ArrayBuffer]': type='arraybuffer';break;
     case '[object SharedArrayBuffer]': type='sharedarraybuffer';break;
     case '[object DataView]': type='dataview';break;

    //Keyed Collection Types:2
     case '[object Map]': type='map';break;
     case '[object WeakMap]': type='weakmap';break;

    //Set Types:2
     case '[object Set]': type='set';break;
     case '[object WeakSet]': type='weakset';break;

    //Operation Types
    case '[object RegExp]': type='regexp';break;
    case '[object Proxy]': type='proxy';break;
    case '[object Promise]': type='promise';break;

    case '[object Object]': type='object';
             if(bReturnConstructor && o.constructor) type=o.constructor.toString().match(/^function\s*([^\s(]+)/)[1];
        type=type.split(' ')[1]

    return type 

You might consider undefined to represent a system-level, unexpected, or error-like absence of value and null to represent program-level, normal, or expected absence of value.

via JavaScript:The Definitive Guide

I'll explain undefined, null and Uncaught ReferenceError:

1 - Uncaught ReferenceError : variable has not been declared in your script, there is no reference to this varaible
2 - undefined: Variable declared but does not initialised
3 - null : Variable declared and is an empty value

Undefined means a variable has been declared but has no value:

var var1;
alert(var1); //undefined
alert(typeof var1); //undefined

Null is an assignment:

var var2= null;
alert(var2); //null
alert(typeof var2); //object

null and undefined are two distinct object types which have the following in common:

  • both can only hold a single value, null and undefined respectively;
  • both have no properties or methods and an attempt to read any properties of either will result in a run-time error (for all other objects, you get value undefined if you try to read a non-existent property);
  • values null and undefined are considered equal to each other and to nothing else by == and != operators.

The similarities however end here. For once, there is a fundamental difference in the way how keywords null and undefined are implemented. This is not obvious, but consider the following example:

var undefined = "foo";
WScript.Echo(undefined); // This will print: foo

undefined, NaN and Infinity are just names of preinitialized "superglobal" variables - they are initialized at run-time and can be overridden by normal global or local variable with the same names.

Now, let's try the same thing with null:

var null = "foo"; // This will cause a compile-time error

Oops! null, true and false are reserved keywords - compiler won't let you use them as variable or property names

Another difference is that undefined is a primitive type, while null is an object type (indicating the absense of an object reference). Consider the following:

WScript.Echo(typeof false); // Will print: boolean
WScript.Echo(typeof 0); // Will print: number
WScript.Echo(typeof ""); // Will print: string
WScript.Echo(typeof {}); // Will print: object
WScript.Echo(typeof undefined); // Will print: undefined
WScript.Echo(typeof null); // (!!!) Will print: object

Also, there is an important difference in the way null and undefined are treated in numeric context:

var a; // declared but uninitialized variables hold the value undefined
WScript.Echo(a === undefined); // Prints: -1

var b = null; // the value null must be explicitly assigned 
WScript.Echo(b === null); // Prints: -1

WScript.Echo(a == b); // Prints: -1 (as expected)
WScript.Echo(a >= b); // Prints: 0 (WTF!?)

WScript.Echo(a >= a); // Prints: 0 (!!!???)
WScript.Echo(isNaN(a)); // Prints: -1 (a evaluates to NaN!)
WScript.Echo(1*a); // Prints: -1.#IND (in Echo output this means NaN)

WScript.Echo(b >= b); // Prints: -1 (as expected)
WScript.Echo(isNaN(b)); // Prints: 0 (b evaluates to a valid number)
WScript.Echo(1*b); // Prints: 0 (b evaluates to 0)

WScript.Echo(a >= 0 && a <= 0); // Prints: 0 (as expected)
WScript.Echo(a == 0); // Prints: 0 (as expected)
WScript.Echo(b >= 0 && b <= 0); // Prints: -1 (as expected)
WScript.Echo(b == 0); // Prints: 0 (!!!)

null becomes 0 when used in arithmetic expressions or numeric comparisons - similarly to false, it is basically just a special kind of "zero". undefined, on the other hand, is a true "nothing" and becomes NaN ("not a number") when you try to use it in numeric context.

Note that null and undefined receive a special treatment from == and != operators, but you can test true numeric equality of a and b with the expression (a >= b && a <= b).


Use null for set a variable you know it is an Object.

Use undefined for set a variable whose type is mixed.

This is my usage of both 5 primitives and Object type, and that explain the difference between « use case » of undefined or null.


If you know a variable is only a string while all lifecycle, by convention, you could initialize it, to "":

("") ? true : false; // false
typeof ""; // "string";
("Hello World") ? true : false; // true
typeof "Hello World"; // "string"


If you know a variable is only a number while all lifecycle, by convention, you could initialize it, to 0 (or NaN if 0 is an important value in your usage):

(0) ? true : false; // false
typeof 0; // "number";
(16) ? true : false; // true
typeof 16; // "number"


(NaN) ? true : false; // false
typeof NaN; // "number";
(16) ? true : false; // true
typeof 16; // "number"


If you know a variable is only a boolean while all lifecycle, by convention, you could initialize it, to false:

(false) ? true : false; // false
typeof false; // "boolean";
(true) ? true : false; // true
typeof true; // "boolean"


If you know a variable is only an Object while all lifecycle, by convention, you could initialize it, to null:

(null) ? true : false; // false
typeof null; // "object";
({}) ? true : false; // true
typeof {}; // "object"

Note: the smart usage off null is to be the falsy version of an Object because an Object is always true, and because typeof null return object. That means typeof myVarObject return consistent value for both Object and null type.


If you know a variable has a mixed type (any type while all lifecycle), by convention, you could initialize it, to undefined.

null is a special value meaning "no value". null is a special object because typeof null returns 'object'.

On the other hand, undefined means that the variable has not been declared, or has not been given a value.

In JavasSript there are 5 primitive data types String , Number , Boolean , null and undefined. I will try to explain with some simple example

lets say we have a simple function

 function test(a) {

     if(a == null){
        alert("a is null");
     } else {
        alert("The value of a is " + a);

also in above function if(a == null) is same as if(!a)

now when we call this function without passing the parameter a

   test(); it will alert "a is null";
   test(4); it will alert "The value of a is " + 4;


var a;
alert(typeof a); 

this will give undefined; we have declared a variable but we have not asigned any value to this variable; but if we write

var a = null;
alert(typeof a); will give alert as object

so null is an object. in a way we have assigned a value null to 'a'

The best way to understand the difference is to first clear your mind of the inner workings of JavaScript and just understand the differences in meaning between:

let supervisor = "None"
    // I have a supervisor named "None"

let supervisor = null
    // I do NOT have a supervisor. It is a FACT that I do not.

let supervisor = undefined
    // I may or may not have a supervisor. I either don't know
    // if I do or not, or I am choosing not to tell you. It is
    // irrelevant or none of your business.

There is a difference in meaning between these three cases, and JavaScript distinguishes the latter two cases with two different values, null and undefined. You are free to use those values explicitly to convey those meanings.

So what are some of the JavaScript-specific issues that arise due to this philosophical basis?

  1. A declared variable without an initializer gets the value undefined because you never said anything about the what the intended value was.

    let supervisor;
    assert(supervisor === undefined);
  2. A property of an object that has never been set evaluates to undefined because no one ever said anything about that property.

    const dog = { name: 'Sparky', age: 2 };
    assert(dog.breed === undefined);
  3. null and undefined are "similar" to each other because Brendan Eich said so. But they are emphatically not equal to each other.

    assert(null == undefined);
    assert(null !== undefined);
  4. null and undefined thankfully have different types. null belongs to the type Null and undefined to the type Undefined. This is in the spec, but you would never know this because of the typeof weirdness which I will not repeat here.

  5. A function reaching the end of its body without an explicit return statement returns undefined since you don't know anything about what it returned.

By the way, there are other forms of "nothingness" in JavaScript (it's good to have studied Philosophy....)

  • NaN
  • Using a variable that has never been declared and receiving a ReferenceError
  • Using a let or const defined local variable in its temporal dead zone and receiving a ReferenceError
  • Empty cells in sparse arrays. Yes these are not even undefined although they compare === to undefined.

    $ node
    > const a = [1, undefined, 2]
    > const b = [1, , 2]
    > a
    [ 1, undefined, 2 ]
    > b
    [ 1, <1 empty item>, 2 ]

For the undefined type, there is one and only one value: undefined.

For the null type, there is one and only one value: null.

So for both of them, the label is both its type and its value.

The difference between them. For example:

  • null is an empty value
  • undefined is a missing value


  • undefined hasn't had a value yet
  • null had a value and doesn't anymore

Actually, null is a special keyword, not an identifier, and thus you cannot treat it as a variable to assign to.

However, undefined is an identifier. In both non-strict mode and strict mode, however, you can create a local variable of the name undefined. But this is one terrible idea!

function foo() {
    undefined = 2; // bad idea!


function foo() {
    "use strict";
    undefined = 2; // TypeError!


When you declare a variable in javascript, it is assigned the value undefined. This means the variable is untouched and can be assigned any value in future. It also implies that you don't know the value that this variable is going to hold at the time of declaration.

Now you can explicitly assign a variable null. It means that the variable does not have any value. For example - Some people don't have a middle name. So in such a case its better to assign the value null to the middlename variable of a person object.

Now suppose that someone is accessing the middlename variable of your person object and it has the value undefined. He wouldn't know if the developer forgot to initialize this variable or if it didn't have any value. If it has the value null, then the user can easily infer that middlename doesn't have any value and it is not an untouched variable.

null and undefined are both are used to represent the absence of some value.

var a = null;

a is initialized and defined.


null is an object in JavaScript

Object.prototype.toString.call(a) // [object Object]

var b;

b is undefined and uninitialized

undefined object properties are also undefined. For example "x" is not defined on object c and if you try to access c.x, it will return undefined.

Generally we assign null to variables not undefined.

Per Ryan Morr's thorough article on this subject...

"Generally, if you need to assign a non-value to a variable or property, pass it to a function, or return it from a function, null is almost always the best option. To put it simply, JavaScript uses undefined and programmers should use null."

See Exploring the Eternal Abyss of Null and Undefined

Both Null and undefined in JavaScript indicate absence of value.

var a = null; //variable assigned null value
var b;  // undefined

Despite the fact both exist for absence of value but: Undefined actually means the variable is not initialized. Functions that return nothing and function parameters for which no value is supplied, undefined value is returned. Use strict equality operator === to distinguish between null and undefined.

Reference: http://www.thesstech.com/javascript/null-and-undefined

OK, we may get confused when we hear about null and undefined, but let's start it simple, they both are falsy and similar in many ways, but weird part of JavaScript, make them a couple of significant differences, for example, typeof null is 'object' while typeof undefined is 'undefined'.

typeof null; //"object"
typeof undefined; //"undefined";

But if you check them with == as below, you see they are both falsy:

null==undefined; //true

Also you can assign null to an object property or to a primitive, while undefined can simply be achieved by not assigning to anything.

I create a quick image to show the differences for you at a glance.

Null and Undefined

As typeof returns undefined, undefined is a type where as null is an initializer indicates the variable points to no object(virtually everything in Javascript is an object).

In javascript all variables are stored as key value pairs. Each variable is stored as variable_name : variable_value/reference.

undefined means a variable has been given a space in memory, but no value is assigned to it. As a best practice, you should not use this type as an assignment.

In that case how to denote when you want a variable to be without value at a later point in the code? You can use the type null ,which is also a type that is used to define the same thing, absence of a value, but it is not the same as undefined, as in this case you actually have the value in memory. That value is null

Both are similar but usage and meaning are different.

I want to add a very subtle difference between null and undefined which is good to know when you are trying to learn Vanilla JavaScript(JS) from ground up:

  • null is a reserved keyword in JS while undefined is a variable on the global object of the run-time environment you're in.

While writing code, this difference is not identifiable as both null and undefined are always used in RHS of a JavaScript statement. But when you use them in LHS of an expression then you can observe this difference easily. So JS interpreter interprets the below code as error:

var null = 'foo'

It gives below error:

Uncaught SyntaxError: Unexpected token null

While below code runs successfully although I won't recommend doing so in real life:

var undefined = 'bar'

This works because undefined is a variable on the global object (browser window object in case of client-side JS)

The difference between undefined and null is minimal, but there is a difference. A variable whose value is undefined has never been initialized. A variable whose value is null was explicitly given a value of null, which means that the variable was explicitly set to have no value. If you compare undefined and null by using the null==undefined expression, they will be equal.

Basically, Undefined is a global variable that javascript create at the run time whether null means that no value has assigned to the variable (actually null is itself an object).

Let's take an example:

        var x;  //we declared a variable x, but no value has been assigned to it.
        document.write(x) //let's print the variable x

Undefined that's what you will get as output.



and you will get 5 as output. That's the main difference between the Undefined and null

null - It is an assignment value, which is used with variable to represent no value (it's an object).

undefined - It is a variable which does not have any value assigned to it, so JavaScript will assign an undefined to it (it's a data type).

undeclared - If a variable is not created at all, it is known as undeclared.

Check this out. The output is worth thousand words.

var b1 = document.getElementById("b1");

checkif("1, no argument"                        );
checkif("2, undefined explicitly",     undefined);
checkif("3, null explicitly",               null);
checkif("4, the 0",                            0);
checkif("5, empty string",                    '');
checkif("6, string",                    "string");
checkif("7, number",                      123456);

function checkif (a1, a2) {
	print("\ncheckif(), " + a1 + ":");
	if (a2 == undefined) {
		print("==undefined:    YES");
	} else {
		print("==undefined:    NO");
	if (a2 === undefined) {
		print("===undefined:   YES");
	} else {
		print("===undefined:   NO");
	if (a2 == null) {
		print("==null:         YES");
	} else {
		print("==null:         NO");
	if (a2 === null) {
		print("===null:        YES");
	} else {
		print("===null:        NO");
	if (a2 == '') {
		print("=='':           YES");
	} else {
		print("=='':           NO");
	if (a2 === '') {
		print("==='':          YES");
	} else {
		print("==='':          NO");
	if (isNaN(a2)) {
		print("isNaN():        YES");
	} else {
		print("isNaN():        NO");
	if (a2) {
		print("if-?:           YES");
	} else {
		print("if-?:           NO");
		print("typeof():       " + typeof(a2));

function print(v) {
	b1.innerHTML += v + "\n";
<!DOCTYPE html>
<pre id="b1"></pre>

See also:


Both special values imply an empty state.

The main difference is that undefined represents the value of a variable that wasn’t yet initialized, while null represents an intentional absence of an object.

The variable number is defined, however, is not assigned with an initial value:

let number;
number; // => undefined

number variable is undefined, which clearly indicates an uninitialized variable

The same uninitialized concept happens when a non-existing object property is accessed:

const obj = { firstName: 'Dmitri' };
obj.lastName; // => undefined

Because lastName property does not exist in obj, JavaScript correctly evaluates obj.lastName to undefined.

In other cases, you know that a variable expects to hold an object or a function to return an object. But for some reason, you can’t instantiate the object. In such a case null is a meaningful indicator of a missing object.

For example, clone() is a function that clones a plain JavaScript object. The function is expected to return an object:

function clone(obj) {
  if (typeof obj === 'object' && obj !== null) {
    return Object.assign({}, obj);
  return null;
clone({name: 'John'}); // => {name: 'John'}
clone(15);             // => null
clone(null);           // => null

However, clone() might be invoked with a non-object argument: 15 or null (or generally a primitive value, null or undefined). In such case, the function cannot create a clone, so it returns null - the indicator of a missing object.

typeof operator makes the distinction between the two values:

typeof undefined; // => 'undefined'
typeof null;      // => 'object'

The strict quality operator === correctly differentiates undefined from null:

let nothing = undefined;
let missingObject = null;
nothing === missingObject; // => false

If a variable is not initialized then it is undefined. undefined is not a object. Example: var MyName; console.log(typeof MyName);

Check the console log in development tool, it will be printed as undefined.

null is a a object.If you want some variable to be null then null is used.null variable exists but value is not known.It should be assigned to a variable pro grammatically. null is not automatically initialized.

Example : var MyName = null; console.log(typeof MyName); Check the csole log in development tool, it will be an object.

Just to add my views -

A variable that is declared only, and never used anywhere, is removed off by an optimizing compiler in case of compiled languages like C++[or a warning is flagged in the IDE]. It ultimately means that the variable is non-existent because it's memory is never allocated.

In case of javascript interpreter, [I guess] a variable is treated as existing only from the point onwards where it is given a value. Before that point, it's type is "undefined", and no memory is allocated for it. And, so its type is undefined.

A null in javascript is a value that represents an address, but that address points to nothing yet[non-existent reference]. Nevertheless, its a value.

In addition to a different meaning there are other differences:

  1. Object destructuring works differently for these two values:
    const { a = "default" } = { a: undefined }; // a is "default"
    const { b = "default" } = { b: null };      // b is null
  2. JSON.stringify() keeps null but omits undefined
    const json = JSON.stringify({ undefinedValue: undefined, nullValue: null });
    console.log(json); // prints {"nullValue":null}
  3. typeof operator
    console.log(typeof undefined); // "undefined"
    console.log(typeof null);      // "object" instead of "null"

Quote from "Eloquent Javascript" 3rd edition by Marijn Haverbeke:

The difference in meaning between undefined and null is an accident of Javascript's design, and it doesn't matter most of the time. In cases where you actually have to concern yourself with these values, I recommend treating them as mostly interchangeable

Honestly, at first, I am a bit skeptical about this advice. However, in my own interpretation, it is a lazy (vs eager) way to deal with their differences. Maybe, we don't have to deal with the differences at all. If we have to, we can delay our concern (util we have to) and not hyperactively/defensively worry about it every step of the way as those values (null and undefined) flow through our code.

PS: This is not a direct answer to your question. This is just a related opinion.