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.
Skills practised: Objects, Methods and dynamic keys.
04Explanation
Bracket notationobj[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().
this is decided by how a function is called, not where it is defined. const f = cart.total; f(); loses this. Arrow functions do not have their own this, so do not use them as methods that need it.
Using objects as dictionaries with user-supplied keys can collide with inherited names such as "constructor" or "__proto__". Use Object.hasOwn(obj, key), Object.create(null) or a Map for arbitrary keys.
Object.fromEntries(entries) turns pairs back into an object, so Object.fromEntries(Object.entries(o).map(...)) transforms an object's values.
Method shorthand (total() { ... }) is preferred in literals; getters (get total() { ... }) expose computed values as properties.
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.
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);
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]);
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
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.
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 explanationdynamic 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 predictiondynamic 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.
Debuggingdynamic 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 generationdynamic 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 reviewdynamic 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.