Arrays are great for lists of similar things. But how do you describe one thing with many details, such as a customer with a name, email and age, or a product with a title, price and stock level? You use an object: a collection of named values.
Objects are everywhere in JavaScript. Data loaded from servers arrives as objects, settings are stored in objects, and the page itself is represented as objects you can change. Once you can create and read objects confidently, most real-world code becomes much easier to follow.
Creating an object
const dog = {
name: "Biscuit",
age: 3,
breed: "Beagle",
isGoodBoy: true,
};- Each entry is a key: value pair, also called a property.
- Keys are names (strings). Values can be anything: numbers, strings, arrays, other objects or functions.
- Separate properties with commas. A comma after the last property is allowed and makes adding new lines easier.
Reading and changing properties
- Dot notation,
dog.name, is the usual way to read a property. - Bracket notation,
dog["name"], is needed when the key is stored in a variable (dog[key]) or contains spaces or hyphens. - Add or change properties with
dog.age = 4;ordog.owner = "Mia";. - Remove a property with
delete dog.breed;. - Reading a property that doesn't exist gives
undefinedrather than an error.
Methods and this
A function stored in an object is called a method. Inside a method, this refers to the object the method belongs to:
const dog = {
name: "Biscuit",
bark() {
return `${this.name} says woof!`;
},
};
dog.bark();Methods keep data and the actions that use it together. You've already used many built-in methods, such as toUpperCase() on strings and push() on arrays.
Working with all the properties
Object.keys(obj)gives an array of the keys.Object.values(obj)gives an array of the values.Object.entries(obj)gives an array of[key, value]pairs."name" in objchecks whether a key exists.for (const key in obj)loops over the keys.
Converting an object to an array with these helpers lets you use array methods like map and filter on its contents.
Optional chaining with ?.
Reading a property of something that might be missing throws an error: user.address.city crashes if address is undefined. Writing user.address?.city safely returns undefined instead. Combine it with ?? for a default value: user.address?.city ?? "Unknown".
JavaScript Objects Syntax
Object basics
const obj = { key: "value", count: 2 };
obj.key; // read
obj["count"]; // read with brackets
obj.newKey = true; // add
delete obj.count; // remove
Object.keys(obj); // ["key", "newKey"]
obj.maybe?.deep; // safe accessJavaScript Objects Summary
- An object stores named properties as key and value pairs.
- Read properties with dot notation, or brackets when the key is in a variable.
- Functions stored in objects are methods, and
thisrefers to the object. Object.keys,Object.valuesandObject.entriesturn objects into arrays.- Optional chaining (
?.) reads nested properties safely.
JavaScript Objects Examples
Each example runs in the page. Edit the code and press Run to see what changes.
A user profile
const user = {
username: "skater_sam",
followers: 128,
interests: ["skating", "music"],
location: { city: "Bristol", country: "UK" },
};
console.log(user.username);
console.log(user["followers"]);
console.log(user.interests[1]);
console.log(user.location.city);
user.followers += 1;
user.verified = true;
console.log(user);Line-by-line explanation
- Lines 1 to 6One object holds strings, numbers, an array and a nested object.
- Lines 8 to 9Dot and bracket notation do the same thing here.
- Line 10Reach into the array.
- Line 11Chain dots to reach into a nested object.
- Lines 13 to 14Update one property and add a new one.
Methods and this
const account = {
owner: "Lin",
balance: 50,
deposit(amount) {
this.balance += amount;
return this.balance;
},
summary() {
return `${this.owner} has £${this.balance}`;
},
};
account.deposit(25);
console.log(account.summary());Line-by-line explanation
- Lines 4 to 7A method;
thisis theaccountobject. - Lines 8 to 10Methods can read other properties through
this.
Keys, entries and optional chaining
const stock = { apples: 12, bananas: 0, cherries: 40 };
console.log(Object.keys(stock));
console.log(Object.values(stock));
for (const [fruit, count] of Object.entries(stock)) {
console.log(`${fruit}: ${count > 0 ? count : "sold out"}`);
}
const field = "cherries";
console.log(stock[field]);
const order = { id: 7 };
console.log(order.delivery?.address ?? "No delivery info");Line-by-line explanation
- Lines 3 to 4Arrays of keys and values.
- Lines 6 to 8Loop over
[key, value]pairs. - Lines 10 to 11Bracket notation with a variable key.
- Line 14
?.avoids a crash becausedeliverydoesn't exist;??gives a default.
Common JavaScript Objects Mistakes
Dot notation with a variable
const key = "age";
console.log(person.key); // looks for a property literally called "key"console.log(person[key]);Reading deep into missing data
const city = user.address.city; // TypeError if address is undefinedconst city = user.address?.city ?? "Unknown";Arrow functions as methods using this
const cat = {
name: "Tom",
hi: () => `I'm ${this.name}`, // this isn't the cat
};const cat = {
name: "Tom",
hi() { return `I'm ${this.name}`; },
};JavaScript Objects in Real Projects
Objects model the real world
Customers, products, messages, settings and game characters are all objects. Data from APIs arrives as objects (written as JSON), and you'll spend a lot of time reading values like response.data.items[0].title.
JavaScript Objects Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Read the city with dot notation, and the country using the variable key.
const place = { city: "Lagos", country: "Nigeria" };
const key = "country";
console.log(place.);
console.log(place[ ]);
place.city uses dot notation; place[key] uses the value stored in key.What does this print?
const car = { brand: "Tesla", year: 2022 };
car.year = 2024;
console.log(car.year, car.color);Which line safely reads user.profile.avatar when profile might not exist?
?. after the part that might be missing.The code should log Mia: 3 pets but crashes and prints the wrong thing. Fix it.
const owner = {
name: "Mia",
pets: ["cat", "rabbit", "fish"],
describe: () => {
return `${this.name}: ${this.pets.lenght} pets`;
},
};
console.log(owner.describe());- Logs "Mia: 3 pets"
- No errors
JavaScript Objects Quiz
3 questions to check what you learned.
What is a property?
- A function
- A key and value pair in an object
- An array index
- A CSS rule
What does
Object.keys({ a: 1, b: 2 })return?- [1, 2]
- 2
- { a, b }
- ["a", "b"]
When must you use bracket notation?
- When the key is stored in a variable or contains spaces/dashes
- Always
- For numbers only
- Never
JavaScript Objects Challenge
Build a game character
Create an object hero with:
name: "Nova",level: 1,inventory: ["sword"]- A method
levelUp()that adds 1 tothis.leveland returns the new level - A method
pickUp(item)that pushesitemintothis.inventory
Then call hero.levelUp() and hero.pickUp("potion"), and log Nova is level 2 with sword, potion.
- hero has the right name
- levelUp increases the level and returns it
- pickUp adds an item
- Logs the summary