Skip to main content

Bracket notation

In JavaScript, object properties can be accessed in two ways: via a dot (.) and via bracket notation ([]).

Here is how the second way, bracket notation, works.


Syntax

javascript
object['key']

Instead of 'key', you can pass a string or a variable holding the property name.


Example 1 - direct access by string

javascript
const user = { name: 'Tim', age: 25 }; console.log(user['name']); // "Tim" console.log(user['age']); // 25

Here 'name' and 'age' are strings that match the object's keys.


Example 2 - access via a variable (dynamic property)

javascript
const key = 'city'; const user = { name: 'Tim', city: 'Kyiv' }; console.log(user[key]); // "Kyiv"

This is the main advantage of bracket notation: you can access properties whose name is stored in a variable. Dot notation (user.key) will not work for this.


Example 3 - a key with spaces or special characters

javascript
const car = { 'car brand': 'BMW', 'engine-type': 'diesel' }; console.log(car['car brand']); // "BMW" console.log(car['engine-type']); // "diesel"

If a property name contains spaces, hyphens, leading digits, or cannot be written as an identifier, it can only be specified using brackets.


Example 4 - nested objects

javascript
const user = { name: 'Tim', address: { city: 'Kyiv' } }; console.log(user['address']['city']); // "Kyiv"

Bracket notation can be used to access nested properties.


When you must use []

SituationWhy
The key is a dynamic value (in a variable)obj[key], not obj.key
The key contains spaces, a hyphen, a number, or a special character'car brand', 'engine-type'
The key is computed by an expressionobj['prefix_' + id]

Summary

WayExampleWhen to use
Dot notationuser.namewhen the key is known in advance and is a valid identifier
Bracket notationuser['name'] or user[key]when the key is dynamic or contains special characters

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.