Object literals and property access

A JavaScript object is a bag of named values. A literal writes the whole bag between two braces, and every field is read either with a dot or with brackets. It is the shape a record takes in this language, and the shape most libraries expect.

This lesson builds literals and reads them in both ways, uses computed keys for names that are only known at run time, and writes methods in the shorthand form. The lessons that follow take the same object apart: its property descriptors in the next one, the static methods of Object after that, then its prototype, and then the classes built on top of it.

A literal and two ways to read it

A literal lists the fields as pairs of a name and a value, and a field whose value is another literal is a nested object. The dot reads a name that is written in the source, and the brackets read a name the program computes, so the two forms are the same operation with a different spelling. A key the object does not have answers undefined rather than failing, and a write to a key that is not there adds it.

The file literal.mjs:

const book = { title: 'The Art of JavaScript', pages: 320, author: { first: 'Ada', last: 'Lovelace' }, tags: ['code', 'math'], }; console.log('the title:', book.title); console.log('the same key with brackets:', book['title']); console.log('a nested field:', book.author.last); console.log('an array field:', book.tags[0], book.tags.length); console.log('a key that is not there:', book.isbn); console.log('the whole object:', JSON.stringify(book)); book.isbn = '978-0-00-000000-0'; delete book.pages; console.log('after a write and a delete:', JSON.stringify(book)); console.log('the pages key is gone:', 'pages' in book);

node literal.mjs

the title: The Art of JavaScript
the same key with brackets: The Art of JavaScript
a nested field: Lovelace
an array field: code 2
a key that is not there: undefined
the whole object: {"title":"The Art of JavaScript","pages":320,"author":{"first":"Ada","last":"Lovelace"},"tags":["code","math"]}
after a write and a delete: {"title":"The Art of JavaScript","author":{"first":"Ada","last":"Lovelace"},"tags":["code","math"],"isbn":"978-0-00-000000-0"}
the pages key is gone: false

Four fields, one nested object and one array, and the read of isbn before the write answered undefined, which is the value a missing key always gives. The write added an eighth field at the end, so the report follows the order of insertion, and the delete removed the pages from both the object and the report. The last line asks a different question, whether any object in the chain has the key, which the lesson on object keys reads in full.

Computed keys

A key written between square brackets in a literal is computed: the expression is evaluated, and its value becomes the key. A template literal builds a name such as chapter3 from a number, which is the usual reason to want one. The same rule turns a number key into text, and a symbol key stays out of the list of keys because a symbol is not a string.

The file computed.mjs:

const field = 'pages'; const chapter = 3; const stats = { [field]: 320, [`chapter${chapter}`]: 'Objects', 42: 'an answer', }; console.log('a key from a variable:', stats.pages); console.log('a key built from a template:', stats.chapter3); console.log('a number key:', stats[42], stats['42']); console.log('the keys in order:', Object.keys(stats).join(',')); console.log('the object itself:', JSON.stringify(stats)); const id = Symbol('id'); const record = { [id]: 7, name: 'Ada' }; console.log('symbols are not in the keys:', Object.keys(record).join(','), record[id]);

node computed.mjs

a key from a variable: 320
a key built from a template: Objects
a number key: an answer an answer
the keys in order: 42,pages,chapter3
the object itself: {"42":"an answer","pages":320,"chapter3":"Objects"}
symbols are not in the keys: name 7

The first two keys came from expressions rather than from names in the source, and they are ordinary keys afterwards: the dot reads stats.pages as it reads any other. The number 42 sits at the front of the list because keys that look like array indexes are ordered as numbers before the rest, which the lesson on objects as maps explains. The symbol is reachable through the variable that holds it and invisible to Object.keys , which is what makes it a name of its own.

Shorthand methods

A field whose value is a function is a method, and a literal can write it in the shorthand form: the name, the parameters and the body, without the function keyword and the colon. Inside the method this is the object the call went through, so counter.bump() changes the counter and counter.report() reads it back, and one method can call another through the same name.

The file methods.mjs:

const counter = { count: 0, bump() { this.count += 1; return this.count; }, report() { return `count is ${this.count}`; }, }; console.log('one bump returns:', counter.bump()); console.log('a second bump returns:', counter.bump()); console.log('a longer report:', counter.report()); console.log('the methods are own keys:', Object.keys(counter).join(',')); const box = { width: 3, height: 4, area() { return this.width * this.height; }, describe() { return `a ${this.width}x${this.height} box with area ${this.area()}`; }, }; console.log(box.describe());

node methods.mjs

one bump returns: 1
a second bump returns: 2
a longer report: count is 2
the methods are own keys: count,bump,report
a 3x4 box with area 12

Two calls changed one field twice, and the report read the value the second call left behind. The fourth line is the part that surprises people: a shorthand method is an ordinary own property, and Object.keys lists it next to the data. The box shows the other half of the idea, a method that calls another method through this.area() rather than repeating the arithmetic.

Two ways a read goes wrong

A read of a key that is missing is safe and gives undefined, but a read of a field of null or undefined throws, because there is no object to look in. The other mistake is a variable used as a key without brackets: order.key asks for a field called key, not for the field whose name the variable holds.

The file mistakes.mjs:

const order = { id: 7, customer: null }; console.log('a field that is null:', order.customer); try { console.log(order.customer.name); } catch (error) { console.log(error.name + ': ' + error.message); } console.log('optional chaining stops at null:', order.customer?.name); const key = 'id'; console.log('a variable name used as a key:', order.key); console.log('the variable taken as a key:', order[key]);

node mistakes.mjs

a field that is null: null
TypeError: Cannot read properties of null (reading 'name')
optional chaining stops at null: undefined
a variable name used as a key: undefined
the variable taken as a key: 7

The error names the value that was null and the key the program asked for, which is enough to find the line in a stack trace. Optional chaining stops the walk at null and answers undefined, and it is the form to write when a missing middle is normal rather than a bug. The last two lines are the same object read twice: the dot gave nothing because there is no field called key, and the brackets gave seven because they used the value of the variable.

Exercises

  1. Add a published field to the book in literal.mjs and read it once with a dot and once with a bracket. Which of the two lines would still work if the name of the field came from a variable?
  2. Build the key chapter3 with plain concatenation instead of a template literal. Does the object change in any way?
  3. Write counter.bump without the call in methods.mjs and print typeof of it. What is the value, and what does it need to run?
  4. Read order.customer.name from mistakes.mjs with order.customer ?? {} in front of it. Does it throw now?
  5. Add a method describe() to the record in computed.mjs that returns a template literal with the symbol value inside it. Why does the symbol still not appear in JSON.stringify?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which two reads give the same value for a key named title?

    Answer

    book.title and book["title"]

    The dot and the brackets with a string are the same read, while the bare name is a variable.

  2. What does { [name]: 1 } do when the variable name holds the string "id"?

    Answer

    It creates the key id with the value 1

    The brackets make the key computed, so the value of the variable becomes the name of the field.

  3. What does a read of a key that the object does not have give?

    Answer

    undefined

    A missing key is not an error on an object, so the read answers undefined.

  4. What is bump() { this.count += 1; } inside an object literal?

    Answer

    A shorthand method, which is an own property holding a function

    The shorthand writes a method without the function keyword, and it is an ordinary own property.

  5. What does this program print? const o = { a: 1, b: 2 }; console.log(o.a + o.b);

    Answer

    3

    The two fields are numbers and the plus adds them.

  6. What does this program print? const o = { a: 1 }; console.log(o.b, typeof o.b);

    Answer

    undefined undefined

    The key was never set, so the read gives undefined and its type is undefined as well.

  7. What does this program print? const k = "x"; const o = { [k]: 1, x: 2 }; console.log(JSON.stringify(o));

    Answer

    {"x":2}

    Both keys are the same string, so the second one wins and overwrites the first value.

  8. What does this program print? const o = { b: 1, 2: 2, a: 3 }; console.log(Object.keys(o).join(","));

    Answer

    2,b,a

    A key that looks like an array index comes first in numeric order, and the rest keep the order of insertion.

  9. What does this program print? const key = "id"; const o = { id: 7 }; console.log(o.key);

    Answer

    undefined

    The dot asks for a field called key, and the value of the variable is not used at all.

  10. What happens when this program runs? const o = { a: null }; console.log(o.a.b);

    Answer

    It throws a TypeError, because null has no fields

    The read of a field of null has no object to look in, so the runtime throws instead of answering.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev