JavaScript Null vs Undefined

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

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

  • false
  • 0 (zero)
  • “” (empty string)
  • null
  • undefined
  • NaN (Not A Number)
  • Boolean
  • Null
  • Undefined
  • Number
  • String
  • Symbol

Deferences between Null and Undefined

null === undefined; // false
null == undefined; // true
var a;
console.log(typeof(a));
// undefined

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

Practical Differences

let logHi = (str = 'hi') => {
console.log(str);
}
logHi();
// hi
logHi('bye');
// bye
logHi(undefined);
// hilogHi(null);
// null

Summery

  • Null is an assigned value. It means nothing.
  • 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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store