JavaScript uses different data types to store and manipulate information. Knowing these types is essential for writing efficient and bug-free code. Data types are divided into primitive and non-primitive types.
1. Primitive Data Types
Primitive types are simple, immutable values stored directly in memory.
- String: Represents textual data. Strings are enclosed in single (
'), double (") or backticks (`).
let name = "Alice";
let greeting = `Hello, ${name}!`; // Template literals
- Number: Represents integers or floating-point numbers.
let age = 30;
let price = 19.99;
- Boolean: Represents
trueorfalse. Often used in conditional statements.
let isActive = true;
if(isActive){
console.log("User is active");
}
- Undefined: A variable declared but not assigned a value.
let city;
console.log(city); // undefined
- Null: Represents intentional absence of a value.
let selectedItem = null;
- Symbol: A unique and immutable value, often used for object property keys.
let id = Symbol("id");
- BigInt: Used for integers larger than
Number.MAX_SAFE_INTEGER.
let bigNumber = 123456789012345678901234567890n;
2. Non-Primitive (Reference) Data Types
These data types store complex data and are mutable.
- Array: Stores ordered collections of values of any type. Arrays come with many built-in methods for manipulation.
let colors = ["red", "green", "blue"];
colors.push("yellow"); // Add element
console.log(colors[2]); // "blue"
- Object: Stores key-value pairs and is used for structured data. Objects can contain strings, numbers, booleans, arrays, functions, or even other objects.
let user = {
name: "Alice",
age: 30,
isActive: true,
hobbies: ["reading", "gaming"]
};
console.log(user.hobbies[1]); // "gaming"
3. Checking Data Types
JavaScript provides the typeof operator to check the type of a variable.
console.log(typeof name); // "string"
console.log(typeof age); // "number"
console.log(typeof user); // "object"
Tip: Arrays are technically objects, so
typeof []returns"object". To check arrays specifically, useArray.isArray(arr).
4. Practical Notes
- Primitive values are immutable — changing a variable creates a new value in memory.
- Objects and arrays are reference types — multiple variables can point to the same object, which may lead to unexpected changes if not handled carefully.
- Understanding data types is crucial for debugging, performing operations, and handling user input in web applications.
Mastering data types in JavaScript is the foundation for everything — from variables and operators to functions and objects.
Citations: