DEV Community

Cover image for Day 8- Undefined, Not defined & null in javascript
C K Sanjay Babu
C K Sanjay Babu

Posted on • Originally published at blog.sanjaybabu.dev on

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.

Undefined

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 :

Hoisting

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

Enter fullscreen mode Exit fullscreen mode

When a method without a return value is assigned.

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

/*
Output:
Hello
Value of str: undefined
*/

Enter fullscreen mode Exit fullscreen mode

Not defined

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

console.log(a);
console.log(b);
var a=10;
let b=100;

/*
Output:
undefined
Uncaught ReferenceError: b is not defined
 */

Enter fullscreen mode Exit fullscreen mode

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

null

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.

Top comments (0)