06. Objects
An object is a collection of key-value pairs. Use it to bundle related data into a single unit.
What you'll learn
- 1Use object literals `{}` to group data together.
- 2Know when to use dot vs bracket notation.
- 3Define methods on an object and use `this` to reach other properties.
- 4Use property shorthand and computed property names.
- 5Write functions that take and return objects.
Overview
An object is a collection of key-value pairs. Use it to bundle related data into a single unit.
Core Concepts
1. Object literals
An object is a collection of key-value pairs. Use it to bundle related data into a single unit.
const user = {
name: "Jimin",
age: 20,
isStudent: true,
};Keys are strings (or Symbols); values can be of any type.
2. Property access: dot vs bracket
Dot notation only works for keys that look like identifiers. Bracket notation lets you use dynamic keys or keys with spaces or special characters.
user.name; // "Jimin"
user["age"]; // 20
const key = "isStudent";
user[key]; // trueReading a non-existent key returns `undefined`. Assigning a new key adds it on the spot.
3. 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.
const counter = {
count: 0,
increment() {
this.count += 1;
},
};
counter.increment();
console.log(counter.count); // 1Arrow functions have no `this` of their own, so they're typically a poor fit for methods (see Lecture 10).
4. Shorthand and computed property names
When the variable and key share a name, you only need to write it once. To compute a key dynamically, put the expression in brackets.
const name = "Minjun";
const age = 25;
const user = { name, age }; // shorthand
const field = "score";
const result = { [field]: 100 }; // computed key β { score: 100 }Examples
| File | What it covers |
|---|---|
| `01_literal.js` | Creating objects, adding/removing properties |
| `02_access.js` | Dot/bracket access, dynamic keys |
| `03_methods.js` | Methods and using this |
| `04_computed.js` | Shorthand and computed properties |
src/01_literal.js
/**
* Object literal basics
*/
"use strict";
const book = {
title: "JS Intro",
pages: 320,
author: "kim",
};
console.log("book =", book);
// Add a property
book.published = 2024;
console.log("after add =", book);
// Delete a property
delete book.author;
console.log("after delete =", book);
src/02_access.js
/**
* Dot vs bracket notation
*/
"use strict";
const product = {
id: 1,
name: "laptop",
"price-krw": 1500000,
};
console.log(product.name);
console.log(product["price-krw"]);
const key = "id";
console.log("dynamic key =", product[key]);
// Missing key
console.log("missing =", product.brand); // undefined
src/03_methods.js
/**
* Methods and this
*/
"use strict";
const cart = {
items: [],
add(item) {
this.items.push(item);
},
total() {
return this.items.reduce((sum, x) => sum + x.price, 0);
},
};
cart.add({ name: "apple", price: 1000 });
cart.add({ name: "bread", price: 2500 });
console.log("items =", cart.items);
console.log("total =", cart.total());
src/04_computed.js
/**
* Shorthand and computed property names
*/
"use strict";
const name = "Sujin";
const age = 22;
const user = { name, age };
console.log("shorthand =", user);
const field = "score";
const value = 95;
const record = { [field]: value, [`${field}_max`]: 100 };
console.log("computed =", record);
Common Mistakes
- Forgetting that even numeric-looking keys are stored as strings internally.
- Getting confused about what `this` will be (method call vs free call).
- Comparing two objects with `===` and being surprised β that's reference equality.
- Confusing `delete obj.key` with `obj.key = undefined`.
- Forgetting that `obj.a.b` throws a TypeError if `a` is missing β use optional chaining `?.`.
FAQ
Q1. What's the difference between an object and a Map?
A Map lets you use any value as a key, preserves insertion order, and has a built-in `size`. For simple data records, a plain object is enough.
Q2. Is property order guaranteed?
Yes β string keys iterate in insertion order, integer-like keys iterate in ascending order (ES2015+).
Q3. Can I mutate the properties of a const object?
Yes β `const` blocks reassignment, not mutation. Use `Object.freeze(obj)` if you need to freeze the contents.
Practice
- `homework_01.js` β Build a user object and add an introduction method.
- `homework_02.js` β Accumulate scores into an object using computed keys.
homework/README.md
## homework_01.js β Build a `user` object that includes:
- Properties: `name`, `age`, `job`
- A method `introduce()` returning `"I'm {name}, a {age}-year-old {job}."`
## homework_02.js β Create an empty `scores` object and a function `addScore(subject, point)`.
- When the same subject is added again, sum its points.
- Print `scores` after each call.
homework/answer/homework_01.js
/**
* Homework 1: user introduction
*/
"use strict";
const user = {
name: "Doyoon",
age: 28,
job: "developer",
introduce() {
return `I'm ${this.name}, a ${this.age}-year-old ${this.job}.`;
},
};
console.log(user.introduce());
homework/answer/homework_02.js
/**
* Homework 2: accumulate scores
*/
"use strict";
const scores = {};
/**
* @param {string} subject
* @param {number} point
*/
function addScore(subject, point) {
scores[subject] = (scores[subject] ?? 0) + point;
}
addScore("math", 80);
addScore("eng", 70);
addScore("math", 10);
console.log(scores); // { math: 90, eng: 70 }
Next Lecture
[07_Arrays_Basics](../07_λ°°μ΄_κΈ°μ΄/) β Working with ordered collections.
All lecture materials and example code are openly available on GitHub.
View on GitHub β