Data types
Every value in JavaScript has a type — the kind of data that determines what you can do with the value. Numbers can be multiplied, strings can be converted to upper case, and booleans can be checked in conditions.
The main types
| Type | Example | Description |
|---|---|---|
number | 42, 3.14 | A number, whole or fractional |
string | 'text' | A string — any text in quotes |
boolean | true, false | A logical value: true or false |
undefined | undefined | No value has been set yet |
null | null | A deliberately empty value |
object | [1, 2], { a: 1 } | Arrays and objects — collections of values |
The first five types are called primitives: simple values that cannot be split further. Arrays and objects get chapters of their own.
The typeof operator
The typeof operator returns the name of a type as a string:
console.log(typeof 42); // numberUse it to check what a variable holds:
console.log(typeof 'text'); // string
console.log(typeof true); // boolean
console.log(typeof undefined); // undefinedBooleans
The boolean type has only two values: true and false. They usually come from comparisons:
console.log(5 > 3); // trueBooleans drive conditions and loops — we will meet them in the next chapter.
undefined and null
A variable that has not been assigned anything holds undefined. You assign null yourself when you want to say explicitly that there is no value:
let city;
const discount = null;
console.log(city); // undefined
console.log(discount); // nullAn easy way to remember: undefined means "not set yet", null means "set, but empty".
The type follows the value
In JavaScript the type belongs to the value, not to the variable. The same variable declared with let can hold a number first and a string later:
let value = 42;
value = 'forty-two';
console.log(typeof value); // stringThis is allowed but best avoided: code is easier to read when a variable always holds data of one type.
Common mistake
typeof has a well-known quirk: for null it returns 'object'. This is a bug from the first versions of the language, kept for compatibility with old websites:
console.log(typeof null); // objectTo check that a value is null, compare it directly: value === null.