What are the data types in JavaScript?

JavaScript has seven primitive types (string, number, bigint, boolean, undefined, null, symbol) and one non-primitive type, object, which includes arrays, functions, dates, maps and everything else.

Primitives

Primitives are immutable and compared by value.

  • string: text, UTF-16 encoded.
  • number: 64-bit floating point, which is why 0.1 + 0.2 !== 0.3. Includes NaN and Infinity.
  • bigint: arbitrary-precision integers, written 123n.
  • boolean: true / false.
  • undefined: a variable that has no value yet.
  • null: an intentional "no value".
  • symbol: a unique identifier, often used as a non-colliding property key.

Objects

Everything that is not a primitive is an object: plain objects, arrays, functions, Date, Map, Set, class instances. Objects are mutable and compared by reference, so two objects with the same contents are not equal.

Auto-boxing

"hi".toUpperCase() works because the engine temporarily wraps the primitive in a String object to call the method. You almost never need new String() yourself.

Gotchas

  • typeof null is "object" (a historical bug).
  • typeof [] is "object"; use Array.isArray.
  • typeof function(){} is "function", though functions are objects.

Code example

js
1// The seven primitives
2console.log(typeof "text", typeof 42, typeof 10n, typeof true); // string number bigint boolean
3console.log(typeof undefined, typeof Symbol("id")); // undefined symbol
4console.log(typeof null); // object <- the famous quirk
5
6// Everything else is an object (functions report "function")
7console.log(typeof { a: 1 }, typeof [1, 2], typeof new Date()); // object object object
8console.log(typeof (() => {})); // function
9console.log(Array.isArray([1, 2])); // true
10console.log(null === null); // true
11
12// Primitives compare by value, objects by reference
13console.log("a" === "a"); // true
14console.log({ a: 1 } === { a: 1 }); // false
15const obj = { a: 1 };
16const sameRef = obj;
17console.log(obj === sameRef); // true
18
19// Floating point
20console.log(0.1 + 0.2); // 0.30000000000000004
21console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON); // true

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app