Day 8- Undefined, Not defined & null in javascript

Day 8- Undefined, Not defined & null in javascript

Javascript handles values that don't or shouldn't exist by the use of undefined, not defined & null keywords. These may seem similar, but there are subtle differences between them.


In JS, undefined is assigned to any variable that has been declared but not yet assigned.

There are many reasons why we get undefined. A few of them are :


All variables declared with var are hoisted in js. So we are able to access them even before declaration but they will return undefined.

Check here for more details about hoisting

When a variable is declared but accessed before its initialized

var count;
console.log(count);     //undefined

When a method without a return value is assigned.

function print(a){
var str=print("Hello");
console.log("Value of str: "+str);

Value of str: undefined

Not defined

not defined error is thrown when a variable is not declared at all.

var a=10;
let b=100;

Uncaught ReferenceError: b is not defined

Note: Again for variable a we got undefined and not an error because of hoisting.


null is an object that can we used to explicitly an empty value.

The difference between null & undefined is that null is an object whereas type of undefined is itself undefined.