An object groups related values under names. Where an array is an ordered list, an object is a set of labelled values: a user's name and email, a course's title and level, a quiz question's text and answer. This lesson covers creating objects, reading and changing their properties, methods, and the bracket notation you need when a key is held in a variable.
Creating an object
Write an object as a list of key: value pairs in curly braces, separated by commas:
const course = {
title: "JavaScript Complete Course",
lessons: 54,
level: "beginner",
published: true,
};
Each pair is a property. The key is the property's name, and the value can be anything: a string, a number, an array, another object or a function. As with arrays, a trailing comma after the last property is allowed.
Keys are strings. You can write them without quotes when they are valid names, as above. Keys with spaces or hyphens need quotes:
const headers = {
"Content-Type": "application/json",
};
Reading properties with dot notation
Read a property by writing the object, a dot and the key:
console.log(course.title);
// JavaScript Complete Course
console.log(course.lessons);
// 54
Reading a property that does not exist gives undefined:
console.log(course.author);
// undefined
Reading a property of undefined or null, however, throws an error:
console.log(course.author.name);
// Uncaught TypeError: Cannot read properties of undefined (reading 'name')
You will see this error often. It means something in the chain is missing. Lesson 25 shows the optional chaining operator, ?., which reads nested data safely.
Adding, updating and removing properties
Assign to a property to update it, or to create it if it does not exist:
const user = { name: "Ada" };
user.name = "Ada Lovelace"; // update
user.role = "admin"; // add
console.log(user);
// { name: "Ada Lovelace", role: "admin" }
As with arrays, this works on a const object. const only stops you replacing the whole object.
Remove a property with delete:
delete user.role;
console.log(user);
// { name: "Ada Lovelace" }
Check whether a property exists with Object.hasOwn() or the in operator. Do not compare with undefined, because a property can exist and hold undefined:
console.log(Object.hasOwn(user, "name"));
// true
console.log("role" in user);
// false
Object.hasOwn() only checks the object's own properties; in also finds inherited ones. Use Object.hasOwn() unless you have a reason not to.
Bracket notation
Bracket notation reads and writes properties using a string inside square brackets:
console.log(course["title"]);
// JavaScript Complete Course
Its real power is that the key can be any expression, including a variable. Dot notation always uses the literal name after the dot:
const field = "level";
console.log(course[field]);
// beginner
console.log(course.field);
// undefined
course.field looks for a property literally called "field". course[field] uses the value of the variable, "level".
Use bracket notation when:
- The key is in a variable, for example a field name chosen by a user or read from a form.
- The key is not a valid name, such as
headers["Content-Type"].
Use dot notation everywhere else; it is shorter and easier to read.
Bracket notation makes objects useful as lookup tables:
const shippingByCountry = {
GB: 3.99,
IE: 6.5,
FR: 8,
};
function getShipping(countryCode) {
return shippingByCountry[countryCode] ?? 12;
}
console.log(getShipping("IE"));
// 6.5
console.log(getShipping("US"));
// 12
The ?? supplies a default when the country is not in the table. Lesson 25 covers it.
Computed keys when creating objects
You can use a variable as a key inside an object literal by wrapping it in square brackets:
const key = "score";
const result = { [key]: 92 };
console.log(result);
// { score: 92 }
Shorthand properties
When a property's value comes from a variable with the same name as the key, you can write the name once:
const name = "Grace";
const role = "admiral";
const person = { name, role };
console.log(person);
// { name: "Grace", role: "admiral" }
{ name, role } is short for { name: name, role: role }. You will see this constantly in modern code.
Methods
A property whose value is a function is called a method. Use the method shorthand to define one:
const basket = {
items: [5, 12.5],
total() {
let sum = 0;
for (const price of this.items) {
sum += price;
}
return sum;
},
};
console.log(basket.total());
// 17.5
Inside a method, this refers to the object the method was called on, so this.items reads the basket's own items. Lesson 21 explains the rules for this in detail. As the last lesson showed, do not use an arrow function for a method that needs this.
You have been calling methods all along: console.log() is the log method of the console object, and "hi".toUpperCase() calls a string method.
Nested objects
Values can be objects or arrays, so you can model structured data:
const lesson = {
title: "Objects",
author: { name: "Ada", country: "GB" },
tags: ["javascript", "objects"],
};
console.log(lesson.author.name);
// Ada
console.log(lesson.tags[0]);
// javascript
Chain dots and brackets to reach deeper values. Keep nesting shallow where you can; deeply nested data is awkward to read and update.
Arrays of objects
The most common data shape in JavaScript is an array of objects that all have the same keys. Every record in a database query, every item in a JSON response, looks like this:
const questions = [
{ id: 1, text: "Which keyword declares a constant?", options: ["let", "const", "var"], answer: "const" },
{ id: 2, text: "What does typeof null return?", options: ["null", "object", "undefined"], answer: "object" },
];
for (const question of questions) {
console.log(`${question.id}. ${question.text}`);
}
// 1. Which keyword declares a constant?
// 2. What does typeof null return?
This is exactly the shape of the quiz app you will start building in the next lesson. Each question is an object with an id, the question text, an array of options and the correct answer.
Looping over an object's properties
To visit every property, use Object.entries() with for...of. It gives you each key and value as a pair:
const settings = { theme: "dark", fontSize: 18 };
for (const [key, value] of Object.entries(settings)) {
console.log(`${key} = ${value}`);
}
// theme = dark
// fontSize = 18
Object.keys() and Object.values() give just the keys or just the values. Lesson 24 covers these and copying objects safely.
Objects are passed by reference
Assigning an object to another variable does not copy it. Both names point to the same object:
const original = { score: 10 };
const alias = original;
alias.score = 99;
console.log(original.score);
// 99
This surprises everyone at first, and it applies to arrays too. Lesson 40 explains why and how to copy safely.
Summary
- Objects hold named properties written as
key: valuepairs in curly braces. - Read and write with dot notation; missing properties give
undefined, but reading throughundefinedthrows. - Use bracket notation when the key is in a variable or is not a valid name.
- Shorthand properties write
{ name }for{ name: name }; computed keys use{ [key]: value }. - Methods are functions stored as properties; inside them,
thisis the object. - Arrays of objects with the same keys are the most common data shape you will work with.