Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

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

TypeExampleDescription
number42, 3.14A number, whole or fractional
string'text'A string — any text in quotes
booleantrue, falseA logical value: true or false
undefinedundefinedNo value has been set yet
nullnullA 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); // number

Use it to check what a variable holds:

console.log(typeof 'text');    // string
console.log(typeof true);      // boolean
console.log(typeof undefined); // undefined

Booleans

The boolean type has only two values: true and false. They usually come from comparisons:

console.log(5 > 3); // true

Booleans 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); // null

An 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); // string

This 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); // object

To check that a value is null, compare it directly: value === null.

Thanks for reading!

Donate to the site — we work hard for you.