JavaScript Data Types

JavaScript data types describe what kind of value a variable holds. There are seven primitive types and one structural type, object. Because JavaScript is dynamically typed, the same variable can hold different types at different times.

The Primitive Types

  • string: text, such as "hello"
  • number: integers and decimals, such as 42 or 3.14
  • bigint: whole numbers of any size, written with n: 9007199254740993n
  • boolean: true or false
  • undefined: a variable that has no value yet
  • null: an intentional "no value"
  • symbol: a unique identifier, mostly used for object keys

Checking Types with typeof

The typeof operator returns the type of a value as a string. Note the famous quirk: typeof null returns "object", a bug kept for backwards compatibility.

console.log(typeof "Lahore");
console.log(typeof 3.5);
console.log(typeof 10n);
console.log(typeof false);
console.log(typeof undefined);
console.log(typeof null);
console.log(typeof Symbol("id"));
console.log(typeof { a: 1 }, typeof [1, 2], typeof function () {});
string
number
bigint
boolean
undefined
object
symbol
object object function

Objects and Arrays

Everything that is not a primitive is an object: plain objects, arrays, functions, dates and more. Use Array.isArray() to tell arrays apart from other objects.

const person = { name: "Omar", age: 28 };
const colors = ["red", "blue"];
console.log(person.name, colors[1]);
console.log(Array.isArray(colors), Array.isArray(person));
Omar blue
true false

Primitive vs Reference Values

Primitives are copied by value. Objects are copied by reference: two variables can point to the same object, so a change through one is visible through the other.

let a = 5;
let b = a;
b = 10;
console.log(a); // 5, unchanged

const o1 = { count: 1 };
const o2 = o1;
o2.count = 99;
console.log(o1.count); // 99, same object
5
99

null vs undefined

undefined usually means "not set by anyone" (a missing property, an argument not passed). null means "deliberately empty", set by the programmer. They are loosely equal (null == undefined) but not strictly equal.

Frequently asked questions

How many data types are there in JavaScript?

Eight: string, number, bigint, boolean, undefined, null, symbol and object. Arrays and functions are special kinds of objects.

Why does typeof null return object?

It is a bug from the first version of JavaScript. Fixing it would break old websites, so it was kept. Check for null with value === null.

Is JavaScript statically or dynamically typed?

Dynamically typed: types belong to values, not variables. TypeScript adds static types on top of JavaScript if you want them.