Sub topic 2
Reading Properties with Dot and Bracket Notation
JavaScript gives you two ways to read a property: dot notation (obj.name) and bracket notation (obj["name"]). They look interchangeable, and in simple cases they are. They differ in what you can write between the dot or the brackets, and in when the key is decided. Most bugs in this area come from mixing up those two differences.
This chapter assumes you know basic JavaScript syntax (variables, functions, template literals) and the primitive types. It also assumes you can create an object with a literal, which the previous chapter covered.
The Two Forms Side by Side
Here is an object with a few kinds of keys, read in both styles:
const car = {
make: "Toyota",
year: 2020,
"top speed": 180,
class: "sedan"
};
console.log(car.make); // "Toyota"
console.log(car["make"]); // "Toyota"
console.log(car["top speed"]); // 180
console.log(car.class); // "sedan"
console.log(car.model); // undefinedThe two notations differ in a few ways:
car.makeandcar["make"]do the same thing. The dot form is shorter and easier to read, so most code uses it whenever it can."top speed"contains a space, so the only way to read it is with brackets.classis a reserved word, but reserved words are allowed after a dot. Since ES5,obj.class,obj.if, andobj.neware all legal.- Reading a property that does not exist gives
undefined. It does not throw an error.
What Dot Notation Accepts
The text after a dot must be a valid identifier name. An identifier name is the same kind of name you could use for a variable: letters, digits, $, and _, and it cannot start with a digit. Reserved words count as identifier names when they come after a dot.
Dot notation is static. The name after the dot is taken literally from the source code. JavaScript never evaluates it.
| Property key | Dot notation | Bracket notation |
|---|---|---|
| `make` | `car.make` | `car["make"]` |
| `top speed` | not possible | `car["top speed"]` |
| `2020` | not possible | `car[2020]` or `car["2020"]` |
| `first-name` | not possible (parsed as subtraction) | `car["first-name"]` |
| `$id` | `car.$id` | `car["$id"]` |
| `class` | `car.class` | `car["class"]` |
| value held in variable `k` | not possible | `car[k]` |
The first-name row deserves a closer look. person.first-name is not a syntax error. JavaScript parses it as person.first - name, which subtracts a variable called name from person.first. If name is not defined, you get a ReferenceError. If it is defined, you get NaN and no error at all.
What Bracket Notation Accepts
Anything that is an expression can go between the brackets. JavaScript evaluates the expression, converts the result to a property key, and then looks that key up. This is why brackets are the tool for dynamic access, where the key is only known at run time.
const scores = { alice: 92, bob: 78, carol: 85 };
function scoreFor(name) {
return scores[name];
}
console.log(scoreFor("bob")); // 78
console.log(scoreFor("dave")); // undefined
const prefix = "car";
console.log(scores[prefix + "ol"]); // 85
for (const name of ["alice", "carol"]) {
console.log(`${name}: ${scores[name]}`);
}
// alice: 92
// carol: 85The expression can be anything: a variable, a concatenation, a function call, or a ternary.
const settings = { light: "#ffffff", dark: "#000000" };
const prefersDark = true;
console.log(settings[prefersDark ? "dark" : "light"]); // "#000000"The most common mistake: dot with a variable
The bug that catches almost everyone is writing a dot where a bracket was meant:
const user = { name: "Lin", email: "[email protected]" };
const field = "email";
console.log(user.field); // undefined: looks for a property literally named "field"
console.log(user[field]); // "[email protected]": uses the value of the variableuser.field never looks at the variable field. It asks for a property whose name is the text field. Because a missing property quietly returns undefined, this bug produces no error. It just gives the wrong answer.
The opposite mistake also happens: user[name] when you meant user["name"]. In that case JavaScript reads whatever the variable name holds. In a browser, the global name is window.name, which is usually an empty string, so the lookup quietly returns undefined again.
How a Bracket Lookup Is Resolved
Bracket access runs in a fixed order. First the object expression is evaluated, then the key expression, then the key is converted, and only then is the property looked up.
Dot access follows the same path, except that the key step is skipped because the key is already fixed in the source.
Key conversion
Property keys are strings or symbols. Symbols get their own chapter. When the bracket expression produces something else, JavaScript converts it to a string. That has some consequences that can surprise you:
const table = { 1: "one", true: "yes", null: "nothing" };
console.log(table[1]); // "one": 1 becomes "1"
console.log(table["1"]); // "one": same key
console.log(table[true]); // "yes": true becomes "true"
console.log(table[null]); // "nothing": null becomes "null"
const a = {};
const b = { x: 1 };
const lookup = {};
lookup[a] = "first";
lookup[b] = "second";
console.log(lookup[a]); // "second"
console.log(Object.keys(lookup)); // ["[object Object]"]Both a and b turn into the string "[object Object]", so the second assignment overwrites the first. A plain object cannot use other objects as keys. If you need that, use a Map.
Reading Nested Properties
A property's value can itself be an object, so you can chain accesses. Each step reads from the result of the step before it, and you can mix dot and bracket notation freely:
const config = {
server: { host: "localhost", port: 8080 },
"feature-flags": { darkMode: true }
};
console.log(config.server.port); // 8080
console.log(config["server"]["host"]); // "localhost"
console.log(config["feature-flags"].darkMode); // true
const section = "server";
const key = "port";
console.log(config[section][key]); // 8080Reading from undefined throws
Reading a missing property is safe. Reading a property of the result is not:
const config = { server: { port: 8080 } };
console.log(config.database); // undefined: no error
try {
console.log(config.database.host);
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message);
// In V8 (Chrome, Node.js):
// "Cannot read properties of undefined (reading 'host')"
}config.database is undefined, and undefined has no properties at all. The same thing happens with null. This is the most common runtime error in JavaScript code that handles data from outside the program, such as API responses or parsed JSON. Optional chaining (?.) fixes it. It is covered with the other existence checks in a later chapter.
Accessing Properties on Primitives
Dot and bracket notation also work on strings, numbers, and booleans, even though those are not objects:
const word = "hello";
console.log(word.length); // 5
console.log(word[0]); // "h"
console.log(word.toUpperCase()); // "HELLO"
console.log((42).toFixed(2)); // "42.00"
console.log(true.toString()); // "true"When you access a property on a primitive, JavaScript temporarily wraps it in an object (String, Number, or Boolean), reads the property from that wrapper, and throws the wrapper away. Only null and undefined have no wrapper, which is why they are the only values that throw when you read a property from them.
The number-literal gotcha
A dot directly after an integer literal is read as a decimal point:
// 42.toFixed(2); // SyntaxError: the parser reads "42." as a number
console.log((42).toFixed(2)); // "42.00"
console.log(42..toFixed(2)); // "42.00": the first dot is the decimal point
console.log(42 .toFixed(2)); // "42.00": the space ends the number
console.log(42["toFixed"](2)); // "42.00"This only affects number literals. A variable holding a number, such as n.toFixed(2), works fine.
Choosing Between Them
Use dot notation by default. It is shorter, linters and editors understand it better, and it tells the reader the key is fixed. Switch to brackets when:
- The key is not a valid identifier, for example
"top speed","first-name", or"2020". - The key comes from a variable, parameter, or expression.
- The key is a symbol. Symbols can only be read with brackets.
Some lint configurations (for example ESLint's dot-notation rule) flag obj["make"] and suggest obj.make. That keeps bracket notation reserved for cases where it is actually needed, so a reader who sees brackets knows something dynamic or unusual is going on.
Exercises
Exercise
Given const item = { id: 3, label: "Pen" }; const prop = "label";, what do item.prop, item[prop], and item["prop"] each return, and why?
Show answer
item.prop returns undefined because it looks for a property literally named "prop". item[prop] returns "Pen" because the variable prop is evaluated to "label". item["prop"] returns undefined because the quoted string "prop" is used as the key, just as in the dot form.
Exercise
What does this log? const m = {}; m[1] = "a"; m["1"] = "b"; m[[1]] = "c"; console.log(Object.keys(m).length, m[1]);
Show answer
It logs 1 "c". The number 1, the string "1", and the array [1] all convert to the property key "1", so each assignment overwrites the same property and the final value is "c".
Exercise
The code const order = JSON.parse('{"customer": null}'); console.log(order.customer.name); crashes. What error is thrown, and which part of the expression causes it?
Show answer
A TypeError is thrown (in V8: "Cannot read properties of null (reading 'name')"). order.customer succeeds and returns null, and reading .name from null throws, because null has no properties and no wrapper object.
Exercise
Write a function pluck(objects, key) that returns an array of the values of key from each object in objects. For example, pluck([{a: 1}, {a: 2}, {}], "a") should return [1, 2, undefined].
Show answer
function pluck(objects, key) { return objects.map(obj => obj[key]); } Bracket notation is required because the key is held in a parameter. Writing obj.key would look up a property literally named "key" and return [undefined, undefined, undefined].