Understand Null and Undefined and their differences

Null and Undefined, two are very important terms in the coding world.

So, let’s learn about Null –

Null basically means if you have nothing to show, you can put null in your code. Look at the example below of Null –

var d = null;

here, the value of variable d is null means nothing. You cannot do anything with this.

Null is not a default value, it must be assigned to show the value of this variable is null.

you cannot do anything with null. it’s just non-existence. Suppose if you do something like this –

console.log(null+4); //4 (result)

you will always get the value which you add or subtract.

Let’s learn about Undefined –

Undefined is basically which is not defined. That’s why it’s called undefined. Understand?

Ok then, let’s look at some example below,

var d;

here, I declared a variable with the name of d. But I’m not defining any value to it right now. So, if u see this variables output, it will give you undefined. cause the value is not defined yet. that’s it.

var d;

console.log(d); //result "undefined";

Undefined is a default value and you also assigned it to something like Null.

Similarities –

  1. In JavaScript, Null and Undefined are both falsy values out of 6 values. Here is the list of falsy values,
  • null
  • undefined
  • 0
  • false
  • “” (empty string)
  • NaN (not a number)

2. They both are primitive values. Look at the all primitive values,

  • string
  • number
  • boolean
  • null
  • undefined
  • symbol (new in ES6)

except these 6, everything is an object in javascript.

But, the main surprising thing is the type of null is an object.

console.log(typeof null); //"object"

This has occurred since the beginning of JavaScript and is generally regarded as a mistake in the original JavaScript implementation.

and the type of undefined is also undefined.

Differences –

  1. Null is not a default value, but undefined is.
  2. if you add or subtract with null, you will get the value itself, but with undefined you will get NaN (Not a Number).
  3. typeof null and undefined are the different value. for null it’s “object” and for undefined it’s “undefined”.

Equality Factor –

If you use the Strict equality or “===”,

console.log(null === null); //return "true"

console.log(undefined === undefined); //return "true"

means if null or undefined is true, then simple equality or “==” is also equal.

but if you compare null with undefined with strict equality, then you will get “false”.

console.log(null === undefined); //returns false;


console.log(null == undefined); //return true;

means their value is same for both but their type is different.

So, that’s all about Null and Undefined. Their similarities and differences. Hope you learn something today.

I’m also learning Javascript. If I mistake somewhere, please mentioned in the comment below.


Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: