Masterbook/Chapter 7• 2 min read
View Raw Code on GitHub

What are data types in JavaScript

What are data types in JavaScript

JavaScript has a small set of built in types. These types define how values behave, how they compare to each other, and what operations are valid. There are primitive types and reference types. Primitive types are immutable and compared by value. Reference types are objects and compared by reference.

The primitive types are number, string, boolean, null, undefined, symbol, and bigint. Number represents both integers and floating point values including special values like NaN and Infinity. String is a sequence of characters. Boolean represents true or false. Null represents an intentional empty value. Undefined means a variable has been declared but not assigned a value. Symbol
creates unique identifiers useful for object keys that should not collide. Bigint represents integers of arbitrary size beyond the safe range of number.

Objects are collections of key value pairs and include plain objects, arrays, functions, dates, and many other built in structures. Functions are callable objects. Arrays are ordered collections with a length property and numeric indices. Most values you create with curly braces or constructors are objects and are passed by reference.

Type inspection can be done with typeof, Array.isArray, and other utilities. typeof works reliably for primitives except that typeof null historically returns object for legacy reasons. Arrays report typeof object, so use Array.isArray to detect them. For class instances, you can use instanceof to check prototype relationships.

Examples

console.log(typeof 42); // "number"
console.log(typeof "hi"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof Symbol("s")); // "symbol"
console.log(typeof 10n); // "bigint"
console.log(typeof null); // "object" (legacy quirk)
console.log(typeof {}); // "object"
console.log(Array.isArray([])); // true
// objects by reference
const a = { x: 1 };
const b = a;
b.x = 2;
console.log(a.x); // 2
// numbers and string conversions
console.log(Number("10")); // 10
console.log(String(99)); // "99"

Common misconceptions

  1. Null and undefined mean the same thing. Null is an intentional empty value; undefined means not assigned yet.
  2. Arrays are a separate typeof result. Arrays are objects; use Array.isArray to detect them.
  3. Bigint and number can be mixed freely. You cannot mix them directly in arithmetic without explicit conversion.

Practice questions

  1. List all primitive types and describe a use case for symbol and bigint.
  2. Why does typeof null return object, and how do you reliably test for null.
  3. When would you prefer an array over an object and why.