Sub topic 2
Reading Properties with Dot and Bracket Notation
This chapter assumes you can write basic JavaScript (variables, functions, if statements), know the primitive types, and can run code in a browser console or Node.js. It also assumes you can create an object literal, which the previous chapter covered.
JavaScript gives you two ways to read a property: dot notation (obj.name) and bracket notation (obj["name"]). Both read the same property. They differ in what you can write after the object.
Dot Notation
Dot notation is short and easy to read. The name after the dot must be a valid identifier. That means it contains only letters, digits, _, or $, and does not start with a digit. Reserved words such as class or default are allowed after a dot.
const book = { title: "Dune", year: 1965, class: "fiction" };
console.log(book.title); // "Dune"
console.log(book.year); // 1965
console.log(book.class); // "fiction" (reserved words are fine after a dot)Bracket Notation
Bracket notation takes any expression. JavaScript evaluates the expression, converts the result to a property key, and looks up that key. You need brackets in three situations:
- The key is not a valid identifier, such as
"page count"or"content-type". - The key starts with a digit, such as
1. - The key is stored in a variable or built at runtime.
const book = { title: "Dune", "page count": 412, 1: "first edition" };
console.log(book["page count"]); // 412
console.log(book[1]); // "first edition"
console.log(book["1"]); // "first edition" (same key)
console.log(book["page" + " count"]); // 412 (expression is evaluated)
const field = "title";
console.log(book[field]); // "Dune"
console.log(book.field); // undefined (looks for a key named "field")The number 1 and the string "1" reach the same property because ordinary keys are stored as strings. The next chapter explains that rule.
Missing Properties and Chained Reads
Reading a property that does not exist does not throw an error. You get undefined. Chained reads go one step at a time, and each step reads from the result of the step before it. If one step gives undefined, the next read throws a TypeError, because null and undefined have no properties.
const order = { customer: { address: { city: "Oslo" } } };
console.log(order.customer.address.city); // "Oslo"
console.log(order["customer"]["address"].city); // "Oslo" (styles can mix)
console.log(order.shipping); // undefined
try {
console.log(order.shipping.city);
} catch (err) {
console.log(err instanceof TypeError); // true
}A later chapter covers optional chaining (?.), which makes this kind of read safe.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| `obj.key` when `key` is a variable | Reads a property literally named `"key"` | Use `obj[key]` |
| `obj[title]` meaning the literal key | Throws `ReferenceError` if `title` is not defined, or reads the wrong key | Use `obj["title"]` or `obj.title` |
| `obj.page count` or `obj.1` | `SyntaxError` | Use `obj["page count"]`, `obj[1]` |
| Reading deep into a missing branch | `TypeError: Cannot read properties of undefined` | Check each level first, or use `?.` |
Exercise
Given const prefs = { theme: "dark", "font-size": 14 }; const k = "theme";, what do prefs.k, prefs[k], and prefs["font-size"] return, and why does prefs.font-size not work?
Show answer
prefs.k returns undefined because it looks up a key named "k". prefs[k] returns "dark" because the variable k is evaluated to "theme". prefs["font-size"] returns 14. prefs.font-size is parsed as prefs.font - size, a subtraction, so it does not read the key "font-size". It gives NaN, or a ReferenceError if no variable named size exists.
Exercise
Write a function getField(obj, name) that returns the property whose key is stored in name, and explain why obj.name would be wrong inside it.
Show answer
function getField(obj, name) { return obj[name]; } Inside the function, obj.name always reads the literal key "name". obj[name] evaluates the parameter and reads whatever key it holds.