Data Types: Primitives and Objects
When working with JavaScript, it’s important to understand the types of data you’ll be dealing with. Every value in JavaScript belongs to one of two categories — primitive types or object types. Knowing the difference between them is key to writing clean, efficient, and bug-free code.
1. Primitives – The Building Blocks
Primitive data types are the most basic and fundamental types in JavaScript. They represent single, immutable values — meaning their actual value cannot be changed once created.
Here are the primitive types in JavaScript:
- Number → Represents numeric values
Example:
10,3.14 - String → Represents text enclosed in quotes
Example:
"hello",'world' - Boolean → Represents logical values
Example:
true,false - Null → Represents an intentional absence of a value
- Undefined → Represents a variable that has been declared but not assigned a value
- Symbol → Represents a unique and immutable value (added in ES6)
- BigInt → Used for very large numbers beyond the safe integer limit (added in ES2020)
Example: Primitive Behavior
let x = 10;
x = 20; // x now holds a new valueIn this example, when we change the value of x, JavaScript doesn’t modify the existing value (10).
Instead, it creates a new primitive value (20) and assigns it to the variable x.
That’s why primitives are considered immutable — their actual values can’t be altered once they exist.
2. Objects – The Complex Data Type
Objects in JavaScript are more powerful and flexible. They can store multiple pieces of data and represent real-world entities like users, cars, or products.
An object is made up of key-value pairs, where:
- Keys are usually strings.
- Values can be any type (including other objects or primitives).
Example: Object Basics
let person = { name: "John", age: 30 };
person.age = 31; // Modifies the existing objectHere, we updated the age property of the person object.
Unlike primitives, objects are mutable, so their contents can be changed without creating a new object.
Other Object Types
In JavaScript, several built-in data structures are also classified as objects:
-
Arrays – Used to store ordered collections of data
let colors = ["red", "green", "blue"]; -
Functions – They are special kinds of objects that can be invoked
function greet() { console.log("Hello!"); } -
Dates – Used to work with date and time
let today = new Date();
All these are technically objects because they store properties and methods that can be modified.
3. Key Difference Between Primitives and Objects
| Feature | Primitives | Objects |
|---|---|---|
| Mutability | Immutable | Mutable |
| Storage | Stores a single value | Stores key-value pairs |
| Copied by | Value | Reference |
| Example | let x = 5 |
let obj = { name: "John" } |
When you copy a primitive, the actual value is copied. But when you copy an object, only the reference (memory address) is copied — meaning both variables point to the same object.