← all writing

Data Types in JavaScript

In JavaScript data types can be divided into two categories.

  1. Primitive data types
  2. Reference data types

Primitive data types

Primitive data types are string, number, boolean, Null, undefined, Symbol.

const str = "deepak";
console.log(typeof str);                 // string
 
const num = 2;
console.log(typeof num);                 // number
 
const bool = true;
console.log(typeof bool);                // boolean
 
var x;
console.log(typeof x);                   // undefined
 
const id = Symbol("id");
console.log(typeof id);                  // symbol
 
console.log(typeof null);                // object

The behavior where typeof null returns 'object' is actually a long-standing quirk or historical mistake in JavaScript. It is considered a bug in the language that cannot be fixed due to backward compatibility reasons.

The typeof operator was designed to return a string indicating the primitive type of a value. However, when applied to null, it incorrectly returns 'object'. This behavior is present in all JavaScript environments, and it has been that way since the early days of the language.

Reference data types

Everything in Javascript is Object except primitive data types.

const date = new Date();
console.log(date instanceof Object);                           // true
 
const arr = ["deepak", "chetan", "narendra"];
console.log(arr instanceof Object);                            // true
 
function myFunction(a, b) {
  return a + b;
}
console.log(myFunction instanceof Object);                     // true
 
const person = {
  name : "deepak",
  place : "bhopal"
};
console.log(person instanceof Object);                         // true

We will learn more about primitive data types in upcoming chapters.

Questions

1. What will be the output of the following program?

console.log(typeof null);

Answer — 'object'