DEV Community

Cover image for Wait... Undefined or Not defined or Null?
Zakaria Elk
Zakaria Elk

Posted on • Updated on

Wait... Undefined or Not defined or Null?

Some of the simplest concepts in JavaScript can be a little tricky to make sense of. One of these is the difference between undefined, not defined and null

Let's start with the easiest one 🤓


Undefined:

There are certain cases where undefined value is returned in javascript such as:

1) Whenever we declare a variable without assigning any value to it, javascript implicitly assigns its value as undefined.

let name;
console.log(name); //undefined

2) When a value is not assigned in an array or object.

let numArray = [1,2,,4];
console.log(numArray);  
//[1, 2, , 4]typeof(numArray[2])
//"undefined"

3) When functions don’t have a return statement but are called for assigning a value to a variable.

let add = (a,b) => {
  let c = a+b;
// no return statement
}let sum = add(2,3);
console.log(sum); 
//Output: undefined

In the code block above, since we commented the return statement, the value of variable sum is given as undefined in the output.


Not defined:

A not defined variable is one which has not been declared at a given point of time with a keyword like var, let or const.

console.log(a);
var a = 5;
//Output:- undefined

While if we don’t use the var declaration, the above the output will look like this:

console.log(b);
b = 5;
//Output:- "ReferenceError: b is not defined

Null:

null is a reserved keyword in javascript. We can assign a null value to a variable explicitly using this keyword. null essentially represents a non-existent or an empty value i.e. we explicitly tell the JavaScript interpreter that the variable has no value.

let life = null;
console.log(life); //null

Top comments (0)