JavaScript + Node.js track

Lesson 06 · Part 2: Objects & Arrays

Objects

Object literals, property access, methods and computed property names

Part 2: Objects & Arrays3 min readFree lesson

Level: Intermediate | Player: 05_Function_Basics

Learning Objectives

  • Data can be expressed in a bundle using the object literal {}.
  • Know the difference between dot notation and square bracket notation.
  • You can define a method on an object and access other properties of the same object through this.
  • Property shorthand and computed property names can be used.
  • You can write a function that receives an object as an argument and returns it.

1. Object literal

An object is a collection of key-value pairs. Used to group related data into one unit.

const user = {
  name: "Jimin",
  age: 20,
  isStudent: true,
};

The key is a string (or symbol) and the value can be any type.

2. Attribute access: dot vs bracket

The dot notation can only be used for keys that can be used as identifiers, and the square bracket notation is used for dynamic keys or keys containing spaces/special-characters.

user.name;          //“Jimin”
user["age"];        // 20
const key = "isStudent";
user[key];          // true

If a non-existent key is read, undefined is returned. When you assign a new key, it is added immediately.

3. Method and this

A property whose value is a function is called a method. this inside the method points to the object that called the method.

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

Arrow functions do not have their own this, so they are usually inappropriate as methods (see Section 10).

4. Shortened notation and calculated attribute names

If the variable name and key name are the same, you only need to use them once. To calculate the key dynamically, write an expression within square brackets.

const name = "Minjun";
const age = 25;
const user = { name, age };                // shorthand
const field = "score";
const result = { [field]: 100 };            // computed key → { score: 100 }

Core example

file Contents covered
01_literal.js Create object, attribute Add/Delete
02_access.js Dot/Bracket access, dynamic key
03_methods.js method, using this
04_computed.js shorthand, computed property

⚠️ Common Mistakes

  1. Forgetting that even though object keys look like numbers, they are stored internally as strings.
  2. I am confused about which object this points to (method call vs. general call).
  3. When comparing objects with ===, it is true only if they are the same reference.
  4. Confuse delete obj.key and obj.key = undefined.
  5. Forgetting to throw TypeError when obj.a.b does not have a in a nested object (using optional chaining ?.).

❓ Frequently Asked Questions (FAQ)

Q1. What is the difference between an object and a Map? A. Map can use any value as a key, order is guaranteed, and size can be known immediately. For simple data structures, objects are sufficient.

Q2. Is the order of object keys guaranteed? A. String keys are traversed in insertion order, and numeric keys are traversed in ascending order (ES2015+).

Q3. Can I change the properties of a const object? A. const only prevents reallocation, it does not prevent internal changes to the object. To freeze, use Object.freeze(obj).

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/01_literal.jsJavaScript
/**
 *Object Literal Basics
 */
"use strict";

const book = {
  title: "Introduction to JS",
  pages: 320,
  author: "kim",
};

console.log("book =", book);

//Add attribute
book.published = 2024;
console.log("after add =", book);

//Delete property
delete book.author;
console.log("after delete =", book);
src/02_access.jsJavaScript
/**
 *Dot notation and 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]);

//non-existent key
console.log("missing =", product.brand); // undefined
src/03_methods.jsJavaScript
/**
 *Method 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.jsJavaScript
/**
 *Shorthand notation and calculated 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);

Assignment

homework_01.js

Create a custom object user and include:

  • Attributes: name, age, job
  • Method introduce() returns “I am {name} and I am {age} and have a {job}.”

homework_02.js

Create an empty object scores and write the function addScore(subject, point).

  • Scores must be added when calling for the same subject.
  • After calling, print scores.
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

homework_01.jsJavaScript
/**
 *Task 1: User self-introduction
 */
"use strict";

const user = {
  name: "Doyun",
  age: 28,
  job: "developer",
  introduce() {
    return `I am ${this.name} and ${this.age} is ${this.job}.`;
  },
};

console.log(user.introduce());
homework_02.jsJavaScript
/**
 *Task 2: Score Accumulation
 */
"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 }

Learn this lesson with a mentor

Work through the JavaScript + Node.js track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now