Primitive types
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',42ortrue. There are exactly seven primitive types. - Objects are collections of values — plain objects, arrays, functions, dates, maps and so on.
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).
let value = 42; // number
value = 'forty-two'; // now a stringThe common ones
const title = 'Arrow functions'; // string
const minutes = 8; // number
const isDone = false; // boolean
let nothingYet; // undefined
const empty = null; // nullstring
Text of any length, written in single quotes, double quotes or backticks. Backticks create template literals, which can include values:
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).
const count = 3;
const price = 4.99;
const big = 1_000_000; // underscores just make it readableboolean
Just two values: true and false. Booleans are the result of comparisons and drive every if and loop.
const isAdult = age >= 18;
const hasItems = cart.length > 0;undefined and null
Both mean “no value”, but they’re used differently:
undefinedis what JavaScript gives you automatically: a declared variable with no value yet, a missing function argument, an object property that doesn’t exist.nullis a value you assign to say “this is intentionally empty”.
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 endsConvention: let JavaScript produce
undefined, and usenullwhen 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:
9007199254740993; // 9007199254740992 — wrong! precision lost
9007199254740993n; // 9007199254740993n — exact
10n * 3n; // 30nYou 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.
const id = Symbol('id');
id === Symbol('id'); // false — every symbol is uniqueChecking a type
The typeof operator tells you a value’s type as a string:
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 bugWatch out:
typeof nullreturns'object'. This is a bug from the very first version of JavaScript that can never be fixed without breaking old websites. To check fornull, compare directly:value === null. To check for an array, useArray.isArray(value).
Primitives are immutable
You can’t change a primitive value in place. String methods, for example, always return a new string:
let word = 'hello';
word.toUpperCase(); // 'HELLO' — a new string
console.log(word); // 'hello' — unchanged
word = word.toUpperCase(); // reassign the variable to keep the new valueThis 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.
'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 unaffectedThis 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.
Describe a value
Write describe(value) that returns 'null' for null, 'array' for arrays, and otherwise the result of typeof.
function describe(value) {
// your code here
}
describe(null); // 'null'
describe([1, 2]); // 'array'
describe('hi'); // 'string'function describe(value) {
if (value === null) return 'null';
if (Array.isArray(value)) return 'array';
return typeof value;
}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.
undefinedmeans “no value yet”;nullmeans “empty on purpose”.- Use
typeofto check what kind of value you have — buttypeof nullis'object'. - Use
Array.isArray()to check for arrays.