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,
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.
- “” (empty string)
- NaN (not a number)
2. They both are primitive values. Look at the all primitive values,
- symbol (new in ES6)
But, the main surprising thing is the type of null is an object.
console.log(typeof null); //"object"
and the type of undefined is also undefined.
- Null is not a default value, but undefined is.
- if you add or subtract with null, you will get the value itself, but with undefined you will get NaN (Not a Number).
- 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.