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
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
*/
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
*/
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.