JS Data Types

JavaScript Data Types: A Complete Guide

A value in JavaScript is always of a certain type. For example, a string or a number. Understanding data types is fundamental to writing effective JavaScript code, as the type of a value determines what you can do with it.


JavaScript is Dynamically Typed

JavaScript is a dynamically typed language. This means that you do not have to declare the type of a variable when you create it. The data type is determined automatically at runtime.

A variable can hold a number one moment and a string the next.

Dynamically Typed Example

// No error
let message = "hello";
console.log(typeof message); // "string"

message = 123456; console.log(typeof message); // "number"


The Two Main Categories of Data Types

There are eight basic data types in JavaScript, which can be divided into two main categories:

1. Primitive Data Types

A primitive data type is data that has a primitive value (it has no properties or methods). There are 7 primitive data types:

2. The Object Data Type (Non-Primitive)

The object type is a non-primitive type. Unlike primitives, objects can store collections of data and more complex entities.

Key Difference: Primitives are immutable (their value cannot be changed, only reassigned) and are compared by their value. Objects are mutable (their contents can be changed) and are compared by their reference (their location in memory).


The typeof Operator

To find the type of a JavaScript variable, you can use the built-in typeof operator.

typeof Operator Example

console.log(typeof "John");         // "string"
console.log(typeof 3.14);           // "number"
console.log(typeof NaN);            // "number"
console.log(typeof false);          // "boolean"
console.log(typeof [1,2,3,4]);      // "object"
console.log(typeof {name:'John'});  // "object"
console.log(typeof new Date());     // "object"
console.log(typeof null);           // "object" (This is a famous bug!)
console.log(typeof undefined);      // "undefined"

In the following chapters, we will explore each of these data types in greater detail.


Exercise

?

Due to a famous historical bug in JavaScript, what does typeof null return?