edubun 한국어

Objects

An object groups related values under names. In { name: "Coco", age: 3 }, pet.name gives "Coco" and pet.age gives 3.

Values with labels

An array is good for a list of similar things in order. Many things in the world are better described by a set of labelled facts: a pet has a name, a kind and an age; a product has a title, a price and a stock count. An object stores exactly that. It is a collection of properties, and each property is a key (the label) paired with a value.

const pet = {
  name: "Coco",
  kind: "cat",
  age: 3,
};
console.log(pet.name);        // Coco
console.log(pet["kind"]);     // cat
console.log(pet.age + 1);     // 4

An object is written in curly braces, with each property as key: value and commas between them. A trailing comma after the last property is allowed. To read a property, write the object, a dot and the key: pet.name. The other form uses square brackets and a string, pet["kind"]. Brackets are needed when the key is stored in a variable, as in pet[field], or when it contains a space. Reading a key that does not exist gives undefined.

Changing and adding properties

Assign to a property to change it, and assign to a new key to add one. As with arrays, this works even when the object was declared with const, because the variable still points to the same object.

const player = { name: "Sam", score: 0 };
player.score += 10;
player.level = 2;
console.log(`${player.name} ${player.score} ${player.level}`);   // Sam 10 2
delete player.level;
console.log(player.level);   // undefined

Lists of objects

Arrays and objects combine naturally. An array of objects is how most programs hold records: a shopping basket, a class list, a set of search results. You loop over the array and read the properties you need from each object.

const basket = [
  { item: "pen", price: 2 },
  { item: "book", price: 12 },
  { item: "bag", price: 25 },
];
let total = 0;
for (const line of basket) {
  total += line.price;
}
console.log("Total:", total);   // Total: 39

Values inside an object can be anything, including arrays and other objects. const user = { name: "Ana", tags: ["admin", "editor"] }; lets you write user.tags[0] to reach "admin". Read such chains from left to right: start at user, go to its tags property, then take index 0.

Methods and the keys of an object

A property whose value is a function is called a method. You have been calling methods all along: console.log is the log method of the console object, and Math.round is the round method of Math. Inside a method, the keyword this refers to the object the method was called on, so a method can read its own object's properties. Finally, Object.keys(pet) gives an array of the keys, here ["name", "kind", "age"], which is useful for looping over every property.

const counter = {
  count: 0,
  add() {
    this.count++;
  },
};
counter.add();
counter.add();
console.log(counter.count);   // 2

Worked example. A book record { title: "Notes", pages: 120, read: 45 } can report progress with Math.round(book.read / book.pages * 100), which is 38, meaning 38 percent. Naming the values pages and read makes the formula readable in a way that b[1] / b[0] never would.

Array or object?

A quick test decides which one to use. If the values are the same kind of thing and their order matters, such as the scores of a class or the steps of a recipe, use an array and reach them by position. If the values are different facts about one thing, such as the name, price and stock of a product, use an object and reach them by name. Most real data mixes the two: an array of products, where each product is an object. When you print an object in the practice box you will see it in a compact form such as {"name":"Coco","age":3}; reading single properties gives cleaner output.

objectA group of named values in { }
propertyOne key: value pair in an object
keyThe name of a property, such as age
dot notationpet.name
bracket notationpet["name"] or pet[field]
methodA property whose value is a function
thisInside a method, the object it was called on
Object.keysAn array of an object's keys
  1. What does this print?
    const car = { brand: "Kia", year: 2020 };
    console.log(car.year);
  2. What does this print?
    const car = { brand: "Kia", year: 2020 };
    console.log(car["brand"]);
  3. What does this print?
    const car = { brand: "Kia" };
    console.log(typeof car.color);
    • undefined
    • An error
    • string
  4. What does this print?
    const box = { w: 4, h: 5 };
    box.w = 6;
    console.log(box.w * box.h);
  5. What does this print?
    const p = { name: "Lee" };
    p.age = 40;
    console.log(Object.keys(p).length);
  6. What does this print?
    const field = "score";
    const r = { score: 88 };
    console.log(r[field]);
  7. What does this print?
    const u = { name: "Ana", tags: ["admin", "editor"] };
    console.log(u.tags[1]);
  8. What does this print?
    const items = [{ n: 2 }, { n: 5 }, { n: 1 }];
    let t = 0;
    for (const it of items) {
      t += it.n;
    }
    console.log(t);
  9. What does this print?
    const c = {
      count: 5,
      add() {
        this.count++;
      },
    };
    c.add();
    console.log(c.count);
  10. Which line adds a property called price with value 9 to the object item?
    • item.price = 9;
    • item = price: 9;
    • item.push(price, 9);
Key points
  • Objects hold key: value properties in { }.
  • Read with obj.key or obj["key"]; brackets for keys in variables.
  • Assign to change or add a property; missing keys read as undefined.
  • Arrays of objects hold records; loop and read each property.
  • A method is a function property; this is its object.