JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 8: Objects and Structured DataLesson 37 of 150About 45 minutes

Lesson 37: Properties, methods and dynamic keys

01Opening question

A form has fields called name, email and phone. How can one line of code read whichever field the user just changed?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Brackets take an expression: the variable field holds the key to read.

const form = { name: "Ada", email: "ada@example.com" };
const field = "email";
console.log(form[field]);
for (const [key, value] of Object.entries(form)) console.log(key, "=", value);

03Objective and prerequisites

Learning objective: Use bracket notation and computed keys for dynamic property names, iterate with Object.keys, values and entries, and add methods that use this.

You need: Lesson 36: Creating JavaScript objects

Skills practised: Objects, Methods and dynamic keys.

04Explanation

Bracket notation obj[key] reads a property whose name is in a variable or has spaces: form[field], scores["team a"].

A computed key in a literal uses brackets too: { [field]: value } creates a property named by the variable's value.

Object.keys(obj) gives an array of keys, Object.values(obj) the values and Object.entries(obj) [key, value] pairs, ready for loops and array methods.

A method is a function stored in a property. Inside a regular method, this is the object the method was called on: cart.total().

05Definitions

Bracket notation
Reading or writing a property with obj[expression].
Computed key
A property name calculated from an expression in [ ] inside an object literal.
Object.entries
Returns an array of [key, value] pairs for an object.
Method
A function stored as a property of an object.
this
Inside a regular method, the object the method was called on.

Open the full glossary

06Visual learning object

Object property inspector. Inspect an object's keys, values and entries and read a property by a key held in a variable.

Loading the interactive object…

Open the full Object property inspector page with its guided experiment.

07Examples

ex-037-01Reading a key from a variable Browser-executable JavaScript

Brackets evaluate the expression inside them.

const prices = { small: 3, medium: 4, large: 5 };
const size = "medium";
console.log(prices[size]);
console.log(prices.size);
console.log(prices["lar" + "ge"]);
Sample input
None
Expected output
4 undefined 5
Common mistake
Writing prices.size, which looks for a key literally named size.
Try this
Read the small price using a variable.
Source
examples/ex-037-01-bracket.js

ex-037-02Computed keys Browser-executable JavaScript

The key name comes from a variable.

function update(state, field, value) {
  return { ...state, [field]: value };
}
const form = { name: "", email: "" };
const next = update(form, "email", "ada@example.com");
console.log(next);
console.log(form.email === "");
Sample input
None
Expected output
{name: "", email: "ada@example.com"} true
Common mistake
Writing { field: value }, which creates a key called field.
Try this
Update the name too.
Source
examples/ex-037-02-computed-key.js

ex-037-03Looping over an object Browser-executable JavaScript

Object.entries gives pairs for a for...of loop.

const stock = { pens: 40, paper: 5, tape: 0 };
for (const [item, qty] of Object.entries(stock)) {
  console.log(`${item}: ${qty === 0 ? "out" : qty}`);
}
const total = Object.values(stock).reduce((a, b) => a + b, 0);
console.log("Units:", total);
Sample input
None
Expected output
pens: 40 paper: 5 tape: out Units: 45
Common mistake
Trying stock.forEach, which objects do not have.
Try this
Print only items with fewer than 10 units.
Source
examples/ex-037-03-entries-loop.js

ex-037-04Methods and this Browser-executable JavaScript

A method reads the object's own data through this.

const cart = {
  items: [4, 10, 6],
  discount: 0.1,
  total() {
    const sum = this.items.reduce((a, b) => a + b, 0);
    return sum * (1 - this.discount);
  }
};
console.log(cart.total());
cart.items.push(10);
console.log(cart.total());
Sample input
None
Expected output
18 27
Common mistake
Writing total: () => ... as an arrow function, where this is not the cart.
Try this
Add an itemCount() method.
Source
examples/ex-037-04-methods-this.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Dot or brackets?

Use bracket notation for a key held in a variable.

const translations = { hello: "bonjour", thanks: "merci" };
const word = "thanks";
console.log(translations.word);

Settings summary

Loop over an object with Object.entries.

const settings = { theme: "dark", fontSize: 16, sounds: false };
// TODO: print each setting as "theme = dark" using Object.entries

Counter with methods

Write an object with methods that use this.

// Create const counter = { count: 0, step: 1, ... } with methods

09Prediction

Commit to an answer first, then run the real code to compare.

const key = "b";
const o = { a: 1, [key]: 2, key: 3 };
console.log(Object.keys(o).join(","), o[key], o.key);

What is printed?

10Debugging investigation

The cart total is NaN when used as a callback

cart.total() works on its own, but passing cart.total to a helper that calls it prints NaN.

const cart = {
  prices: [10, 20],
  total() {
    let sum = 0;
    for (const p of this?.prices ?? [NaN]) sum += p;
    return sum;
  }
};
function show(getTotal) {
  console.log("Total:", getTotal());
}
show(cart.total);

More cases in the Debugging Detective Laboratory

11Practical scenario

Generic form handler

One input handler updates any form field: it reads the field's name from the input and writes state[name] = value. Adding a new field to the form needs no new JavaScript.

const state = { name: "", email: "" };
function onInput(name, value) { state[name] = value; }
onInput("email", "ada@example.com");
console.log(state);

12Knowledge check

1. What is printed?

const o = { x: 2 };
const k = "x";
console.log(o[k]);
  • 2
  • undefined
  • k
  • An error

2. What does Object.entries({ a: 1 }) return?

  • ["a"]
  • [1]
  • [["a", 1]]
  • {a: 1}

3. What is printed?

const user = { name: "Ada", hi: () => this?.name };
console.log(user.hi());
  • Ada
  • undefined
  • An error
  • name

4. Why does the object get a key called "field"?

const field = "email";
const next = { ...form, field: value };
  • Brackets are missing around field in the literal
  • field is undefined
  • Spread is wrong
  • Objects cannot be updated

5. What is printed?

console.log(Object.values({ a: 1, b: 2 }).reduce((s, v) => s + v, 0));
  • 3
  • [1, 2]
  • 12
  • undefined

6. Keys come from user input (any string). Which is safest?

  • A plain object {}
  • A Map
  • An array
  • A string

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Dot or brackets?: Prints merci
  • Settings summary: Prints three lines; Uses Object.entries
  • Counter with methods: Prints 6 then 0; increment returns the count; setStep chains
  • ex-037-01: output matches the documented expected output
  • ex-037-02: output matches the documented expected output
  • ex-037-03: output matches the documented expected output
  • ex-037-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-08-objects-and-structured-data/lesson-037-properties-methods-and-dynamic-keys/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • obj[key] reads a property whose name is in a variable.
  • { [key]: value } builds a computed key.
  • Object.keys, values and entries turn objects into arrays.
  • Methods use this to reach their object; avoid arrow functions as methods.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation dynamic keys and methods
Context: I am learning dynamic keys and methods in JavaScript.
Task: Explain bracket notation, computed keys, Object.entries and methods with this, using a settings object.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction dynamic keys and methods drill
Context: I have practised dynamic keys and methods.
Task: Give me six snippets with dynamic keys and this and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging dynamic keys and methods bug
Context: My object gets a property literally called field instead of the field's name.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation dynamic keys and methods practice
Context: I finished the dynamic keys and methods exercises.
Task: Create three exercises that loop over objects and use dynamic keys.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review dynamic keys and methods review
Context: Here is my code that uses dynamic keys and methods.
Task: Review my object code for dot-vs-bracket mistakes and for methods written as arrow functions.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.