Objects
An object groups related data and behaviour under one name, using key–value pairs. A student, a product, an M-Pesa transaction or the settings of an app are all natural objects. Objects are at the heart of JavaScript: arrays, functions and even the web page itself are objects.
Creating objects and reading properties
The easiest way to make an object is an object literal: curly braces holding key: value pairs separated by commas. Each pair is a property.
const student = {
name: "Amina",
age: 20,
county: "Mombasa",
"favourite subject": "Biology"
};
console.log(student.name);
console.log(student["age"]);
console.log(student["favourite subject"]);
const key = "county";
console.log(student[key]);
console.log(student.phone);
Dot notation (student.name) is the normal choice. Use bracket notation (student["age"]) when the key contains spaces or dashes, or when the key is stored in a variable, as with student[key]. Reading a property that doesn't exist gives undefined, not an error.
Adding, changing and removing properties
const phone = { brand: "Tecno", price: 15000 };
phone.price = 13500; // change
phone.colour = "blue"; // add
delete phone.brand; // remove
console.log(phone);
console.log("price" in phone);
console.log(Object.hasOwn(phone, "brand"));
Notice phone is a const, yet we changed it. const only stops you pointing phone at a different object; the object's contents can still change. To check whether a property exists, use the in operator or Object.hasOwn(). For nested data that might be missing, optional chaining (user.address?.town) reads safely.
Methods and this
A property whose value is a function is called a method. Inside a method, this refers to the object the method was called on. The shorthand deposit(amount) { ... } is the modern way to write methods.
const account = {
owner: "Chebet",
balance: 2000,
deposit(amount) {
this.balance += amount;
return this.balance;
},
summary() {
return `${this.owner} has KES ${this.balance}`;
}
};
console.log(account.deposit(500));
console.log(account.summary());
Use regular method syntax rather than arrow functions for methods that use this; see Arrow Functions for why. When you need many objects of the same shape, classes give you a blueprint.
Looping over an object
Object.keys(), Object.values() and Object.entries() turn an object into arrays you can loop over:
const marks = { maths: 78, english: 85, kiswahili: 91 };
console.log(Object.keys(marks));
console.log(Object.values(marks));
for (const [subject, mark] of Object.entries(marks)) {
console.log(`${subject}: ${mark}`);
}
Object.entries() gives an array of [key, value] pairs, and const [subject, mark] unpacks each pair (array destructuring, covered on the Arrays page).
Destructuring
Destructuring pulls properties out into variables in one line. You can rename a property with a colon and provide a default with =:
const user = { name: "Brian", age: 23, town: "Kisii" };
const { name, age } = user;
console.log(name, age);
const { town: homeTown, job = "student" } = user;
console.log(homeTown, job);
function introduce({ name, town }) {
return `${name} from ${town}`;
}
console.log(introduce(user));
Destructuring in a function's parameter list, as in introduce, is very common: the function clearly states which properties it needs.
Shorthand and spread
If a variable has the same name as the key you want, write it once: { title, salary } means { title: title, salary: salary }. The spread syntax ... copies all properties of one object into a new one. Later properties overwrite earlier ones, which is perfect for applying a user's choices on top of defaults:
const title = "Intern";
const salary = 25000;
console.log({ title, salary });
const defaults = { theme: "light", language: "en", notifications: true };
const choices = { theme: "dark", language: "sw" };
const settings = { ...defaults, ...choices };
console.log(settings);
Spread makes a shallow copy: nested objects are still shared. After const copy = { ...original };, changing copy.name is safe, but changing copy.address.town also changes original.address.town, because both point to the same inner address object. For a full deep copy, use structuredClone(original).
Key points
- Objects store key–value properties; read them with dot or bracket notation.
- Properties can be added, changed and deleted, even on a
constobject. - Methods are function properties; inside them
thisis the object they were called on. Object.keys,valuesandentrieshelp you loop; destructuring unpacks properties into variables.- Spread
{ ...a, ...b }copies and merges objects, but only shallowly.
Tip: use the ← and → keys to move between pages.
