Primitive types

Topic 2 of 5 in Variables & types7 min readBeginnerFree course

Overview

Every value in JavaScript has a type, and the type decides what you can do with it: you can multiply numbers, make strings upper-case, and call functions — but not the other way round.

There are two big families of values:

  • Primitives hold a single, simple piece of data, such as 'hello', 42 or true. There are exactly seven primitive types.
  • Objects are collections of values — plain objects, arrays, functions, dates, maps and so on.

All values split into primitives — string, number, boolean, undefined, null, bigint and symbol — and objects, such as plain objects, arrays, functions, Date and Map.

JavaScript is dynamically typed: a variable doesn’t have a fixed type; the value it currently holds does. The same let can hold a number now and a string later (although doing that on purpose usually makes code harder to follow).

JavaScript
let value = 42;      // number
value = 'forty-two'; // now a string

The common ones

JavaScript
const title = 'Arrow functions'; // string
const minutes = 8;               // number
const isDone = false;            // boolean
let nothingYet;                  // undefined
const empty = null;              // null

string

Text of any length, written in single quotes, double quotes or backticks. Backticks create template literals, which can include values:

JavaScript
const name = 'Asha';
console.log(`Welcome back, ${name}!`);

You’ll explore strings in depth in the Strings topic.

number

Whole numbers and decimals share one type. It also includes three special values: Infinity, -Infinity and NaN (“not a number”, the result of failed maths).

JavaScript
const count = 3;
const price = 4.99;
const big = 1_000_000; // underscores just make it readable

boolean

Just two values: true and false. Booleans are the result of comparisons and drive every if and loop.

JavaScript
const isAdult = age >= 18;
const hasItems = cart.length > 0;

undefined and null

Both mean “no value”, but they’re used differently:

  • undefined is what JavaScript gives you automatically: a declared variable with no value yet, a missing function argument, an object property that doesn’t exist.
  • null is a value you assign to say “this is intentionally empty”.
JavaScript
let selected;            // undefined — nothing chosen yet
const user = { name: 'Asha' };
user.age;                // undefined — property doesn't exist

let winner = null;       // deliberately empty until the game ends

Convention: let JavaScript produce undefined, and use null when you want to clear a value yourself.

The rarer ones

bigint

Numbers are exact only up to Number.MAX_SAFE_INTEGER (9,007,199,254,740,991). For bigger whole numbers — IDs from some databases, cryptography — add n to make a BigInt:

JavaScript
9007199254740993;   // 9007199254740992 — wrong! precision lost
9007199254740993n;  // 9007199254740993n — exact
10n * 3n;           // 30n

You can’t mix BigInt and ordinary numbers in maths (10n + 1 throws); convert one side first.

symbol

A symbol is a guaranteed-unique value, mostly used as a special object key that can never clash with other keys. You’ll meet them properly in the Symbols topic.

JavaScript
const id = Symbol('id');
id === Symbol('id'); // false — every symbol is unique

Checking a type

The typeof operator tells you a value’s type as a string:

JavaScript
typeof 'hi';         // 'string'
typeof 42;           // 'number'
typeof 42n;          // 'bigint'
typeof true;         // 'boolean'
typeof undefined;    // 'undefined'
typeof Symbol();     // 'symbol'
typeof {};           // 'object'
typeof [];           // 'object'   — arrays are objects
typeof function(){}; // 'function' — a special case of object
typeof null;         // 'object'   — a historical bug

Watch out: typeof null returns 'object'. This is a bug from the very first version of JavaScript that can never be fixed without breaking old websites. To check for null, compare directly: value === null. To check for an array, use Array.isArray(value).

Primitives are immutable

You can’t change a primitive value in place. String methods, for example, always return a new string:

JavaScript
let word = 'hello';
word.toUpperCase(); // 'HELLO' — a new string
console.log(word);  // 'hello' — unchanged

word = word.toUpperCase(); // reassign the variable to keep the new value

This is different from objects, which can be changed after they’re created.

Value versus reference

Primitives are copied and compared by value: two equal-looking primitives are equal. Objects are compared by reference: two objects are only equal if they are the very same object.

JavaScript
'abc' === 'abc';          // true
{ a: 1 } === { a: 1 };    // false — two different objects
[1, 2] === [1, 2];        // false

let a = 5;
let b = a;   // copies the value 5
b = 6;
console.log(a); // 5 — a is unaffected

This difference explains a lot of surprising behaviour later, so keep it in mind. The Spread and copying and Equality and immutability topics come back to it.

Wrapper objects

You may have noticed that primitives have methods: 'hi'.toUpperCase(), (3.14159).toFixed(2). When you call a method on a primitive, JavaScript briefly wraps it in an object (String, Number, Boolean) to find the method, then throws the wrapper away.

You never need to create wrappers yourself — avoid new String('hi') and new Number(5), which create objects that behave strangely in comparisons. The plain functions String(value) and Number(value) (without new) are fine: they convert values, as you’ll see in Type coercion.

Exercise

Describe a value

Write describe(value) that returns 'null' for null, 'array' for arrays, and otherwise the result of typeof.

JavaScript
function describe(value) {
  // your code here
}

describe(null);     // 'null'
describe([1, 2]);   // 'array'
describe('hi');     // 'string'

Summary

  • The primitives are string, number, bigint, boolean, undefined, null and symbol. Everything else is an object.
  • Primitives are immutable and compared by value; objects are compared by reference.
  • undefined means “no value yet”; null means “empty on purpose”.
  • Use typeof to check what kind of value you have — but typeof null is 'object'.
  • Use Array.isArray() to check for arrays.