JavaScript Null vs Undefined

So Lets Get Started.

……………………

Introduction

What Is Null ?

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

How to check for Null

const missingObject = null;
const existingObject = { message: 'Hello!' };

missingObject === null; // => true
existingObject === null; // => false

missingObject === null evaluates to true because missingObject variable contains a null value.

If the variable contains a non-null value, like an object, the expression existingObject === null evaluates to false.

What is Undefined ?

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

How to check for Undefined

let var1;if (var1 === undefined) {console.log("var1 is undefined")} else {console.log("var1 holds some value")}
// var1 is undefined

Similarities between Null and Undefined

Here is six falsy value list :

  • false
  • 0 (zero)
  • “” (empty string)
  • null
  • undefined
  • NaN (Not A Number)

Also in JavaScript, there are six primitive values. Both Null and Undefined are primitive values.

Here is six primitive value list :

  • Boolean
  • Null
  • Undefined
  • Number
  • String
  • Symbol

All other values in JavaScript are objects (objects, functions, arrays, etc.).

Deferences between Null and Undefined

Deferences :

The strict equality operator === distinguishes Null from Undefined :

null === undefined; // false

While loose equality operator == considers Null and Undefined equal :

null == undefined; // true

……………………………………………………………………………………….

Null and undefined are both primitives and falsy values. However, null is also an object.

var a;
console.log(typeof(a));
// undefined

var b = null;
console.log(typeof(b));
// object

Practical Differences

let logHi = (str = 'hi') => {
console.log(str);
}

The code above creates a function named logHi. This function requires one parameter and sets the default of that parameter to hi if it isn’t supplied. Here’s what that looks like :

logHi();
// hi

We can also supply a parameter to overwrite this default :

logHi('bye');
// bye

With default parameters, undefined will use the default while null does not.

logHi(undefined);
// hilogHi(null);
// null

Summery

  • Undefined typically means a variable has been declared but not defined yet.
  • Null and undefined are falsy values.
  • Null and undefined are both primitives. However, an error shows that typeof null = object.
  • null !== undefined but null == undefined.