Objects
Why it matters
An array stores a list in order. But how do you describe one thing with many characteristics — for example, a user with a name, age and city? That's what an object is for: a set of "key — value" pairs. Almost everything in JavaScript is an object: data from a server, settings, products, messages. It's the most important data structure of the language.
Creating and reading
const user = {
name: "Anna",
age: 15,
city: "Khujand",
};
console.log(user.name); // Anna — with a dot
console.log(user["city"]); // Khujand — with square brackets
console.log(user.email); // undefined — no such property
key: value pairs are listed with commas inside curly braces. Keys are also called properties.
Dot or brackets? Usually a dot. Square brackets are needed when the key name is in a variable or contains a space or a hyphen:
const field = "age";
console.log(user[field]); // 15
const car = { "max-speed": 220 };
console.log(car["max-speed"]); // 220
Changing, adding, deleting
const user = { name: "Anna", age: 15 };
user.age = 16; // change
user.city = "Dushanbe"; // add a new one
delete user.name; // delete
console.log(user);
Output:
{"age":16,"city":"Dushanbe"}
As with arrays, const doesn't prevent changing an object's contents — it only forbids putting another object into the variable.
Checking whether a property exists
const settings = { theme: "dark", volume: 0 };
console.log("theme" in settings); // true
console.log("lang" in settings); // false
console.log(settings.volume ?? 50); // 0 — ?? doesn't confuse 0 with "missing"
Shorthand
If the variable name matches the key name, you can write it once:
const name = "Timur";
const age = 17;
const user = { name, age }; // same as { name: name, age: age }
console.log(user);
Output:
{"name":"Timur","age":17}
Looping over an object
const prices = { tea: 50, coffee: 90, juice: 70 };
for (const key in prices) {
console.log(key, prices[key]);
}
console.log(Object.keys(prices)); // keys
console.log(Object.values(prices)); // values
console.log(Object.entries(prices)); // [key, value] pairs
Output:
tea 50
coffee 90
juice 70
["tea","coffee","juice"]
[50,90,70]
[["tea",50],["coffee",90],["juice",70]]
Object.keys/values/entries return arrays, so all array methods work with them:
Object.values(prices).reduce((s, p) => s + p, 0) → 210.
Nesting and arrays of objects
A property's value can be anything — an array, another object:
const student = {
name: "Ira",
marks: [5, 4, 5],
address: { city: "Bokhtar", street: "Rudaki" },
};
console.log(student.address.city);
console.log(student.marks[1]);
Output:
Bokhtar
4
A very common structure is an array of objects: a list of products, users, messages.
Methods and this
If a property's value is a function, it's called a method:
const counter = {
value: 0,
increase() {
this.value++;
},
};
counter.increase();
counter.increase();
console.log(counter.value);
Output:
2
this inside a method is the object the method was called on (here counter). For methods use this
short syntax or function, but not an arrow: arrow functions have no this of their own.
How it works inside
An object is like a cabinet with labelled drawers: a drawer is found by its label (key) immediately,
without going through all of them. That's why obj[key] is very fast even for huge objects — which is why
objects are handy for counting and grouping. Object keys are always strings (numbers are turned into
strings): obj[1] and obj["1"] are the same property.
A variable stores not the object but a reference to it — just like with arrays. const b = a doesn't
copy the object: a and b point to the same one. Copying is in the next topic.
Common mistakes
- A dot with a variable.
obj.key, when the key name is in the variablekey, looks for a property named"key". You needobj[key]. - A missing comma between properties.
{ a: 1 b: 2 }is a syntax error. =instead of:inside an object.{ name = "Anna" }is an error. Inside an object — a colon.- Adding to something that doesn't exist.
counts[word]++for a new word givesNaN(undefined + 1). Start with0:(counts[word] ?? 0) + 1. - An arrow as a method using
this.{ go: () => this.x }—thiswon't be the object.
Cheat sheet
| What | How |
|---|---|
| Create | const o = { a: 1, b: "x" }; |
| Read | o.a, o["a"], o[key] |
| Change / add | o.a = 2; o.c = true; |
| Delete | delete o.a |
| Exists? | "a" in o |
| Shorthand | { name, age } |
| Loop | for (const k in o), Object.keys/values/entries(o) |
| Method | { go() { this.x++; } } |