Concept Explanation
An Array is a numbered list — you find things by position (0, 1, 2). An Object is different: it is a labeled drawer. Instead of numbers, you use names (called keys) to store and find values.
Think of an object as an ID card. It doesn't say "item 0 is Alice, item 1 is 30." It says name: "Alice", age: 30. Every piece of data carries a clear label, so your code reads like plain English.
Objects are the most important data type in JavaScript — arrays, functions, even the browser's document are all secretly objects underneath.
Syntax or Core Structure
Creating, Reading, and Changing
const user = {
name: "Alice",
age: 30,
isAdmin: false,
greet() {
return `Hi, I'm ${this.name}`; // "this" = the object itself
}
};
// Two ways to read a value:
console.log(user.name); // Dot notation -> "Alice"
console.log(user["age"]); // Bracket notation -> 30
// Add, update, and delete:
user.email = "alice@mail.com"; // add a new key
user.age = 31; // update
delete user.isAdmin; // remove
Use dot notation for keys you already know. Use bracket notation when the key lives in a variable: user[fieldName].
Looping Over an Object
const scores = { math: 90, science: 85 };
for (const subject in scores) {
console.log(`${subject}: ${scores[subject]}`);
}
Object.keys(scores); // ["math", "science"]
Object.values(scores); // [90, 85]
Real World Example
Every response from a server (an API) is an object. When a profile page loads, the server sends something like { "name": "Alice", "followers": 1200, "verified": true }. Your JavaScript reads profile.followers to paint the number on screen. No objects, no modern web.
Common Mistakes
- Dynamic keys with dot notation:
user.myVarlooks for a key literally named "myVar", not the value stored insidemyVar. Useuser[myVar]for variables. - Comparing objects with ===:
{a:1} === {a:1}isfalse! Objects are compared by reference (memory address), not by their contents. - Forgetting
this: Inside a method you must writethis.name, not justname, to reach the object's own data.
Best Practices
- Shorthand properties: If a variable name matches the key, write
{ name }instead of{ name: name }. - Optional chaining: Use
user?.address?.cityto read deep values safely without crashing when something is missing. - Freeze constants:
Object.freeze(config)blocks accidental changes to objects that should never change. - Destructure to unpack: Pull values out cleanly with
const { name, age } = user;.
Practice Exercises
- The Profile Card: Build a
personobject withname,age, and ahobbiesarray. Print a sentence describing them. - The Inventory: Create a
productobject, then write code that adds adiscountkey only if the price is above 100. - The Word Counter: Given an array of words, build an object that counts how many times each word appears.