Difference between undefined, not defined & null in javascript

This topic is one of the famous interview questions so therefore we are here to cover this in our blog. Without wasting any time let's move on to the main part.

How undefined Work?

Undefined is returned by the javascript compiler when a particular value whose value is defined till now is console logged. Here are some examples:

  1. When we try to access value before initializing it

     let myvalue;
     console.log(myvalue);
    
  2. When we try to access the return value of the function but nothing is returned

     function myfunc(){
         // perform some operations but doesn't returns any value
     }
     let res=myfunc();
     console.log(res);
    
  3. When we try to access the value at any index in an array that is not defined

     let arr=[0,1,2];
     console.log(arr[5]);
    

How does null Work?

"null" is a type of value that can be assigned by us to any variable & it is also a reserved keyword for the same reason. Assigning null means we are explicitly telling the javascript interpreter that there is no value.

let success = null;
console.log(success);

How does not defined Work?

"not defined" means that the particular has not been declared inside the program written by the user. Here is an example of code and its output.

Code:

let var_a;
let var_b;
console.log(var_c);

Output:

ReferenceError: var_c is not defined

Interview Question: What is the difference between the outputs of the below code?

Code Example 1:

console.log(a); 
var a;

Code Example 2:

console.log(b);
b;

Think for at least 5 minutes before scrolling below and looking at the answer.

Answer: In the 1st example the output will be undefined and in the 2nd example the output will be not defined. The reason for the 1st output is hoisting and easy to understand. Now in the 2nd output, we are declaring the variable without the
"var" keyword and it is declared like window.b.

I hope you were able to understand the concepts clearly. Feel free to ask your doubts and share your thoughts in the comment box.