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

PartRule
Braces{ opens, } closes
KeyIdentifier (no quotes needed) or string literal (quotes needed for special chars)
ColonSeparates key from value
CommaSeparates pairs; trailing comma is allowed and recommended
ValuesAny 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:

PrimitivesObjects (Reference types)
Typesstring, number, bigint, boolean, undefined, null, symbolobject (including arrays, functions, dates, etc.)
Stored asThe value itselfA reference (memory address) pointing to the value
Copied byValue — independent copyReference — both variables point to the same data
Compared byValue5 === 5 is trueReference{} === {} is false
Mutable?No — you replace, not modifyYes — 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

Valuetypeof resultIs 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

FeaturePlain object {}Map
Key typesStrings and Symbols onlyAny value (objects, functions, primitives)
Key orderInsertion order (with numeric key caveat)Strict insertion order
SizeObject.keys(obj).lengthmap.size (property)
PerformanceGood for small/medium sizesOptimized for frequent add/delete
JSON supportNative JSON.stringifyRequires manual conversion
When to useConfig, models, API dataDynamic 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 fieldsData is a list of similar items
Order is not primary concernOrder matters (first, second, third...)
Access by key nameAccess by numeric index
Example: { name: "Alice", age: 25 }Example: ["Alice", "Bob", "Charlie"]
Modeling a single entityModeling 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 thingObject 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

  1. An object is a collection of key-value pairs — the fundamental grouping structure in JavaScript.
  2. Use object literal syntax { key: value } for quick, readable creation.
  3. Objects are reference types — assigning an object to another variable creates a shared reference, not a copy.
  4. Primitives get temporary wrapper objects (autoboxing) so you can call methods like .toUpperCase().
  5. typeof {} returns "object", but so does typeof [] and typeof null — use Array.isArray and null checks for precision.
  6. {} !== {} — every literal creates a new reference; content comparison requires manual logic.
  7. Use objects for named/keyed data, arrays for ordered lists, and arrays of objects for collections of entities.

Explain-It Challenge

Explain without notes:

  1. 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.
  2. Why does {} === {} evaluate to false?
  3. 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 →