Emmanuel Akinfulubi

JavaScriptBasic

Dot notation vs bracket notation in JavaScript

Beginner · 4 min read

There are two ways to read a property from an object in JavaScript. You can write a dot, passenger.name, or square brackets with the name in quotes, passenger['name']. Most of the time they do exactly the same thing. The interesting part is the few cases where only one of them works.

In this tutorial you will read the same property both ways, then read a key held in a variable, a key with a space in it, and a key that is a number. You will also see why two different objects used as keys overwrite each other. You need to know what an object is and how to make a variable.

Two spellings, one property

An object is a set of named values. The name is called a key. Here is a passenger with three keys:

JavaScript

const passenger = { name: 'Adaeze', 'seat number': 'B3', fares: {} };
console.log(passenger.name);    // Adaeze
console.log(passenger['name']); // Adaeze

The dot is shorter and easier to read, so it is the normal choice. Brackets are the general tool: inside them you can put any expression, and JavaScript works out the key name from it.

The rule for the dot

After a dot you must write the name itself, and it has to be a valid identifier: letters, digits, _ or $, not starting with a digit, no spaces. passenger.name is fine. passenger.seat number is not, because of the space.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

83 Dot notation and bracket notation

easy

Read the same property with a dot and with brackets. Then read a key held in a variable, a key with a space in it, and a numeric key.

Stuck? Three hints, smallest first
  1. 1. Dot notation needs a literal name that is a valid identifier.
  2. 2. Brackets take any expression, so a variable holding the key name works there and only there.
  3. 3. Every key is a string. Watch what happens to one that is not.

Step 1: a key held in a variable

Say the key you want is stored in a variable called field. Try both spellings:

Step 1

const passenger = { name: 'Adaeze', 'seat number': 'B3', fares: {} };
const field = 'name';
console.log(passenger[field]); // Adaeze
console.log(passenger.field);  // undefined

The brackets read the variable, find 'name' inside it, and look up that key. The dot does not read variables at all. passenger.field looks for a key literally called "field", finds none, and gives undefined without any error. That silence is the trap: nothing tells you the lookup went wrong.

This is why loops over Object.keys and lookup tables use brackets. The key changes on every turn, so it has to live in a variable.

Step 2: a key with a space

Step 2

const passenger = { name: 'Adaeze', 'seat number': 'B3', fares: {} };
console.log(passenger['seat number']); // B3

A key that isn't a valid identifier has to be quoted when you create it and read with brackets. There is no dot version. Keys like this often turn up in data you didn't design, such as a spreadsheet column called "seat number".

Step 3: set a nested key

You can chain lookups to reach inside an object that sits inside another object:

Step 3

const passenger = { name: 'Adaeze', 'seat number': 'B3', fares: {} };
passenger.fares.yaba = 200_00;
console.log(passenger.fares.yaba); // 20000

200_00 is 20,000 kobo (₦200); the underscore only helps you read it. This works because fares already exists as an empty object. If it didn't, passenger.fares would be undefined, and setting .yaba on undefined throws a TypeError. The parent has to exist first.

Step 4: number keys become text

Every object key is a string. If you use a number, JavaScript turns it into text before storing it:

Step 4

const seats = {};
seats[3] = 'taken';
console.log(Object.keys(seats));       // [ '3' ]
console.log(seats[3] === seats['3']);  // true

3 was stored as '3'. So seats[3] and seats['3'] are the same property. You can't write seats.3, though: 3 isn't a valid identifier, so that line is a syntax error.

Step 5: objects as keys collide

The same conversion happens to any value you use as a key, including an object. An object turned into text becomes "[object Object]", every time:

Step 5

const odd = {};
odd[{ a: 1 }] = 'first';
odd[{ b: 2 }] = 'second';
console.log(Object.keys(odd));        // [ '[object Object]' ]
console.log(odd['[object Object]']);  // second

Two different objects, one key. The second write replaced the first. If you need real objects as keys, use a Map, which keeps each key as it is.

The full solution

The answer panel reads the passenger's name both ways, reads keys from a variable and with a space, sets a nested fare, and shows number keys and object keys being turned into strings. Press Run to see the output.

The answer

const passenger = {
  name: 'Adaeze',
  'seat number': 'B3',           // a space, so brackets are the only way in
  fares: {},
};

const field = 'name';

passenger.fares.yaba = 200_00;   // the parent has to exist first

// A number key is stored as a string, so both spellings reach it.
const seats = {};
seats[3] = 'taken';

// So is any other value used as a key, which is how two objects collide.
const odd = {};
odd[{ a: 1 }] = 'first';
odd[{ b: 2 }] = 'second';        // same key: "[object Object]"

console.log(passenger['seat number'], passenger[field], passenger.field);
console.log('object keys collapse to', Object.keys(odd));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('dot and bracket read the same key', passenger.name === passenger['name'], true);
test('brackets take a variable key', passenger[field], 'Adaeze');
test('a dot with the same name looks for a literal key called field', passenger.field, undefined);
test('a key with a space needs brackets', passenger['seat number'], 'B3');
test('a number key is stored as a string', Object.keys(seats), ['3']);
test('so either spelling reaches it', seats[3] === seats['3'], true);
test('any other key is stringified too, so these two collide', Object.keys(odd).length, 1);
test('and the second write won', odd['[object Object]'], 'second');
test('a nested key set through its parent', passenger.fares.yaba, 20000);

Dot notation is the readable default and cannot do three things: use a name held in a variable, use a name that is not a valid identifier ('seat number'), or use a name built at runtime. Brackets do all three, which is why lookup tables and loops over Object.keys are written with them.

passenger.field returning undefined rather than throwing is the trap: the dot took field as a literal key name, found none, and said nothing. And keys are always strings — seats[3] and seats['3'] are one property, and two different objects used as keys both stringify to "[object Object]" and overwrite each other. When you need object identity in a key, that is what Map is for.

Common mistakes

  • Writing obj.key when key is a variable. The dot reads a key named "key". Use obj[key].
  • Forgetting the quotes inside brackets. passenger[name] looks for a variable called name. To read the key itself, write passenger['name'].
  • Using objects as keys in a plain object. They all become "[object Object]" and overwrite each other. Use a Map.

Try it yourself

  1. Make an array ['name', 'seat number'] and loop over it, printing each value from passenger with brackets.
  2. Write getField(obj, key) that returns obj[key], or 'missing' when the key isn't there.
  3. Build the key at runtime: with const day = 'mon', set passenger[day + 'Fare'] = 150_00 and print Object.keys(passenger).

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.