Skip to content
Topic 12 of 16
Theory

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

  1. A dot with a variable. obj.key, when the key name is in the variable key, looks for a property named "key". You need obj[key].
  2. A missing comma between properties. { a: 1 b: 2 } is a syntax error.
  3. = instead of : inside an object. { name = "Anna" } is an error. Inside an object — a colon.
  4. Adding to something that doesn't exist. counts[word]++ for a new word gives NaN (undefined + 1). Start with 0: (counts[word] ?? 0) + 1.
  5. An arrow as a method using this. { go: () => this.x } — this won'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++; } }

A user

Easy+10 XP

Write a function makeUser(name, age) that returns an object with three properties:

  • name — the name;
  • age — the age;
  • isAdult — true if the age is 18 or more, otherwise false.
makeUser("Anna", 19)  → { name: "Anna", age: 19, isAdult: true }

Connect the connector to solve tasks

Task code runs on your own computer — faster and more reliable than in the browser. This needs the free CodeWithMe connector app. You only connect it once.

Looking for the connector on this computer…

  1. 1
    Download the connector for your system (Windows, macOS or Linux).Download the connectorOn the download page pick the file with your system in its name, e.g. windows-amd64.
  2. 2Run it and choose a folder for your solutions. It will install Python and Node.js there by itself when needed.
  3. 3
    Enter below the 6-digit code shown in the connector window (“Code for CodeWithMe”). If the browser asks about local network access — allow it.

The connector is open source (on GitHub), works only on your computer and runs code only after you enter the pairing code.