Whether you are building your first web application or optimizing complex code, understanding what are JavaScript data types is fundamental to mastering the language. JavaScript powers the modern web, and every value processed by your scripts belongs to a specific classification that determines how it behaves, stores data, and interacts with other code elements.
In this comprehensive guide, we will break down all the JavaScript data types you need to know. From primitive values to complex reference objects, you will explore how data types in JavaScript work under the hood through real-world code examples and detailed explanations.
Understanding JavaScript Data Types
There is no restriction in JavaScript when you declare a variable to a specific data type. In other words, JavaScript uses dynamic typing in which variables may have values of any data type and their types may change at runtime.
While considering the JavaScript data types, they fall into two broad classifications:
- Primitive Data Types (immutable, stored by value)
- Reference / Non-Primitive Data Types (mutable, stored by reference)
Let’s break down each type with code examples and detailed descriptions.
1. Primitive Data Types
The primitive data types consist of single, constant values. When you perform any operation on a primitive type, you operate on the actual value.
A. String
String is a data type that represents a piece of text. It can be surrounded by single quotes (‘), double quotes (“), or backticks (‘).
let firstName = “Jane”;
let lastName = ‘Doe’;
let greeting = `Hello, ${firstName} ${lastName}!`;
console.log(greeting); // Output: Hello, Jane Doe!
console.log(typeof greeting); // Output: string
B. Number
JavaScript employs just one type to store numbers, and these can be integers and floating-point numbers. There are also some other unique numbers in JavaScript, like Infinity, -Infinity, and NaN (Not-a-Number).
let integerNum = 42;
let floatNum = 3.14;
let negativeNum = -100;
let calculation = 10 / 0; // Infinity
console.log(typeof integerNum); // Output: number
console.log(calculation); // Output: Infinity
C.BigInt
BigInt is introduced to have integers represented with arbitrary precision, enabling numbers that exceed the highest safe integer (Number.MAX_SAFE_INTEGER) to be expressed. You simply add the letter “n” to an integer literal.
let normalMax = Number.MAX_SAFE_INTEGER;
let bigNumber = 9007199254740991n;
let evenBigger = BigInt(“900719925474099123456789”);
console.log(typeof bigNumber); // Output: bigint
D. Boolean
A boolean represents a logical entity with only two possible values: true or false. They are commonly used in conditional statements and control flow.
let isLoggedIn = true;
let hasAdminAccess = false;
if (isLoggedIn) {
console.log(“Welcome back!”);
} else {
console.log(“Please log in.”);
}
E. Undefined
A variable that has been declared but has not yet been assigned a value automatically holds the value undefined.
let userScore;
console.log(userScore); // Output: undefined
console.log(typeof userScore); // Output: undefined
F. Null
The null value is the explicit presence of no value. Unlike undefined, it has to be explicitly assigned.
let selectedUser = null;
console.log(selectedUser); // Output: null
// Note: typeof null returns ‘object’ due to a historical bug in JavaScript
console.log(typeof selectedUser); // Output: object
G. Symbol
Symbol was introduced in ES6; it is an immutable and unique identifier. Symbol is generally used as unique property keys to avoid name conflicts.
let uniqueId = Symbol(“id”);
let user = {
name: “Alice”,
[uniqueId]: 12345
};
console.log(user[uniqueId]); // Output: 12345
console.log(typeof uniqueId); // Output: symbol
2. Reference (Non-Primitive) Data Types
To understand properly what are JavaScript data types, it is important to be familiar with reference data types such as objects, arrays, and functions. These complicated data types in JavaScript help to store data collections, complex data, and reusable code. Reference data types are stored in memory using pointers.
A. Object
An object is a collection of key-value pairs (properties and methods). It is the most versatile data structure in JavaScript.
let car = {
brand: “Tesla”,
model: “Model 3”,
year: 2024,
startEngine: function() {
return “Engine started!”;
}
};
console.log(car.brand); // Output: Tesla
console.log(car.startEngine()); // Output: Engine started!
console.log(typeof car); // Output: object
B. Array
An array is an example of an object that can be used for storing a sequence of items. Arrays may contain various data types such as integers, strings, as well as arrays themselves.
let fruits = [“apple”, “banana”, “cherry”];
let mixedArray = [42, “hello”, { active: true }, [1, 2]];
console.log(fruits[0]); // Output: apple
console.log(fruits.length); // Output: 3
console.log(typeof fruits); // Output: object
C. Function
In JavaScript, functions are objects that can be called. Functions being first-class objects means that they can be stored in variables, passed as parameters, and returned from functions.
function multiply(a, b) {
return a * b;
}
let result = multiply(5, 4);
console.log(result); // Output: 20
console.log(typeof multiply); // Output: function
Best Practices of JavaScript Data Types
Below is the list of best practices in handling JavaScript data types:
- Use strict equality (===) always: Do not use loose equality (==), which causes implicit type coercion (such as ‘0’ == false will evaluate to true).
- Immutability via const: Always declare variables with const unless there is a need to reassign their value. Never use var.
- Convert type explicitly: Always use explicit conversions via String(), Number(), or Boolean() methods. Do not use dynamic type coercions such as +val or val + ”.
- Check for NaN properly: Do not check for NaN with the equality operator, as NaN === NaN evaluates to false. Instead, use Number.isNaN() to verify a non-number result.
- Beware of typeof null: Be aware that typeof null returns ‘object’. To test if the variable contains null, you should use val === null directly.
- Use primitive over objects: Never use constructors to create primitives. For example, you should not use new String() or new Number(), but instead create primitive values.
- Protect from object mutation: Use Object.freeze() or Object.assign() / spread (… ) operators while handling objects and arrays.
Conclusion
One of the core features of JavaScript data types is dynamic typing, which offers great flexibility but can occasionally lead to unexpected type coercion bugs (e.g., “5” + 5 resulting in “55”).
Knowing what are JavaScript data types and how to inspect them using the typeof operator will make you a much stronger programmer. Mastering these JavaScript data types and various data types in JavaScript ensures robust code and helps you write cleaner, more maintainable applications.
