Episode 1 — Fundamentals / 1.23 — Objects
1.23.a — What is an Object?
In one sentence: An object is a collection of key-value pairs that models real-world entities, giving JavaScript its primary way to group related data and behavior under a single reference.
Navigation: ← 1.23 Overview · 1.23.b — Key-Value Pairs →
1. Objects as a real-world modeling tool
Think of a person's ID card. It has fields — name, date of birth, photo, ID number. Each field has a label (key) and a value. A JavaScript object works the same way:
const idCard = {
name: "Alice Johnson",
dateOfBirth: "1998-03-15",
idNumber: "A-123456",
photo: "alice.jpg"
};
Every real-world "thing" with named properties maps naturally to an object: a product in a catalog, a user profile, a configuration file, an API response.
2. Object literal syntax
The most common way to create an object is the object literal — curly braces with comma-separated key-value pairs:
const user = {
name: "Alice",
age: 25,
isAdmin: false
};
Syntax rules
| Part | Rule |
|---|---|
| Braces | { opens, } closes |
| Key | Identifier (no quotes needed) or string literal (quotes needed for special chars) |
| Colon | Separates key from value |
| Comma | Separates pairs; trailing comma is allowed and recommended |
| Values | Any valid JS expression — number, string, boolean, array, object, function, null |
// Trailing comma — perfectly valid and helps with cleaner diffs
const config = {
theme: "dark",
fontSize: 16,
showSidebar: true, // <-- trailing comma
};
Empty object
const empty = {};
console.log(empty); // {}
3. Objects vs primitives — reference types
JavaScript has two categories of data:
| Primitives | Objects (Reference types) | |
|---|---|---|
| Types | string, number, bigint, boolean, undefined, null, symbol | object (including arrays, functions, dates, etc.) |
| Stored as | The value itself | A reference (memory address) pointing to the value |
| Copied by | Value — independent copy | Reference — both variables point to the same data |
| Compared by | Value — 5 === 5 is true | Reference — {} === {} is false |
| Mutable? | No — you replace, not modify | Yes — you can change properties in place |
// Primitive — copy by value
let a = 10;
let b = a; // b gets its OWN copy of 10
b = 20;
console.log(a); // 10 — unchanged
// Object — copy by reference
let obj1 = { name: "Alice" };
let obj2 = obj1; // obj2 points to the SAME object
obj2.name = "Bob";
console.log(obj1.name); // "Bob" — both see the change!
This reference behavior is one of the most common sources of bugs for beginners.
4. Everything in JS "is" (or behaves like) an object
You may have heard the phrase "everything in JavaScript is an object." That is an oversimplification, but it captures an important truth:
// Strings are primitives, yet you can call methods on them
const greeting = "hello";
console.log(greeting.toUpperCase()); // "HELLO"
How? JavaScript temporarily wraps the primitive in a wrapper object (String, Number, Boolean) behind the scenes, calls the method, then discards the wrapper. This is called autoboxing.
// What JS does internally (conceptually):
// new String("hello").toUpperCase() → "HELLO" → wrapper discarded
What truly IS an object
| Value | typeof result | Is it an object? |
|---|---|---|
{} | "object" | Yes |
[] | "object" | Yes (arrays are objects) |
function() {} | "function" | Yes (functions are objects) |
new Date() | "object" | Yes |
null | "object" | No — this is a famous JS bug |
"hello" | "string" | No — primitive (but autoboxes) |
42 | "number" | No — primitive (but autoboxes) |
true | "boolean" | No — primitive (but autoboxes) |
undefined | "undefined" | No |
Symbol() | "symbol" | No — primitive |
5. Object as a hash map / dictionary
In computer science, a hash map (or dictionary) stores data as key-value pairs with fast lookup by key. JavaScript objects serve this role:
// Using an object as a dictionary / lookup table
const countryCapitals = {
France: "Paris",
Japan: "Tokyo",
Brazil: "Brasilia",
India: "New Delhi",
};
console.log(countryCapitals["Japan"]); // "Tokyo" — O(1) lookup
When to use an object as a map vs Map
| Feature | Plain object {} | Map |
|---|---|---|
| Key types | Strings and Symbols only | Any value (objects, functions, primitives) |
| Key order | Insertion order (with numeric key caveat) | Strict insertion order |
| Size | Object.keys(obj).length | map.size (property) |
| Performance | Good for small/medium sizes | Optimized for frequent add/delete |
| JSON support | Native JSON.stringify | Requires manual conversion |
| When to use | Config, models, API data | Dynamic lookups, non-string keys |
For most everyday use (user profiles, settings, API responses), plain objects are the standard choice.
6. When to use objects vs arrays
| Use an Object when... | Use an Array when... |
|---|---|
| Data has named fields | Data is a list of similar items |
| Order is not primary concern | Order matters (first, second, third...) |
| Access by key name | Access by numeric index |
Example: { name: "Alice", age: 25 } | Example: ["Alice", "Bob", "Charlie"] |
| Modeling a single entity | Modeling a collection of entities |
Often you combine both: an array of objects.
// Array of objects — the most common data pattern in JS
const users = [
{ id: 1, name: "Alice", role: "admin" },
{ id: 2, name: "Bob", role: "editor" },
{ id: 3, name: "Charlie", role: "viewer" },
];
// Find a specific user
const admin = users.find(u => u.role === "admin");
console.log(admin.name); // "Alice"
7. typeof with objects
console.log(typeof {}); // "object"
console.log(typeof []); // "object" — arrays are objects!
console.log(typeof null); // "object" — historical bug
console.log(typeof function(){}); // "function" — special case
// To check for a "plain" object specifically:
console.log(Array.isArray([])); // true — use this to distinguish arrays
console.log(Array.isArray({})); // false
Reliable type checks
function isPlainObject(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
console.log(isPlainObject({})); // true
console.log(isPlainObject([])); // false
console.log(isPlainObject(null)); // false
console.log(isPlainObject("hello")); // false
8. Object identity — {} !== {}
Every time you write {}, JavaScript creates a new object in memory with a new reference. Two objects are only === if they point to the same memory:
const a = { name: "Alice" };
const b = { name: "Alice" };
const c = a;
console.log(a === b); // false — different objects in memory
console.log(a === c); // true — same reference
// Even empty objects:
console.log({} === {}); // false — two distinct objects
This means you cannot compare objects with === to check if they have the same contents. You need to compare property by property (shallow equality) or use a deep comparison utility.
// Simple shallow equality check
function shallowEqual(obj1, obj2) {
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) return false;
return keys1.every(key => obj1[key] === obj2[key]);
}
console.log(shallowEqual({ x: 1 }, { x: 1 })); // true
console.log(shallowEqual({ x: 1 }, { x: 2 })); // false
9. Real-world analogies
| Real-world thing | Object representation |
|---|---|
| ID card | { name, dob, photo, idNumber } |
| Product catalog entry | { sku, title, price, inStock, category } |
| Restaurant menu item | { dish, description, price, allergens: [...] } |
| Weather API response | { city, temp, humidity, forecast: [...] } |
10. Real examples
User profile
const userProfile = {
id: 42,
username: "alice_dev",
email: "alice@example.com",
isVerified: true,
joinDate: "2023-01-15",
followers: 1280,
bio: "Full-stack developer. Coffee enthusiast.",
};
Configuration settings
const appConfig = {
apiUrl: "https://api.example.com",
timeout: 5000,
retries: 3,
debug: false,
theme: "dark",
features: {
notifications: true,
darkMode: true,
betaFeatures: false,
},
};
API response
const apiResponse = {
status: 200,
ok: true,
data: {
user: {
id: 1,
name: "Alice",
posts: [
{ id: 101, title: "Hello World", likes: 15 },
{ id: 102, title: "Learning JS", likes: 42 },
],
},
},
timestamp: "2025-04-10T12:00:00Z",
};
Key takeaways
- An object is a collection of key-value pairs — the fundamental grouping structure in JavaScript.
- Use object literal syntax
{ key: value }for quick, readable creation. - Objects are reference types — assigning an object to another variable creates a shared reference, not a copy.
- Primitives get temporary wrapper objects (autoboxing) so you can call methods like
.toUpperCase(). typeof {}returns"object", but so doestypeof []andtypeof null— useArray.isArrayand null checks for precision.{} !== {}— every literal creates a new reference; content comparison requires manual logic.- Use objects for named/keyed data, arrays for ordered lists, and arrays of objects for collections of entities.
Explain-It Challenge
Explain without notes:
- What is the difference between a primitive and a reference type? Give an example showing how changing one variable affects (or does not affect) another.
- Why does
{} === {}evaluate tofalse? - When would you choose an object over an array to store data? Give a real-world example of each.
Navigation: ← 1.23 Overview · 1.23.b — Key-Value Pairs →