The Bracket [ ] Operator
Example
// Create an Object
const user = { name: "Alice" };
// Access a property using a string literal
let name1 = user["name"];
// Access a property using a variable
let key = "name";
let name2 = user[key];
Try it Yourself »
Definition
The [ ] operator is used to access object properties or array elements.
It allows you to look up values using strings, variables, or evaluations.
Dot Notation vs Bracket Notation
In JavaScript, both Dot Notation (object.property) and Bracket Notation (object["property"]) are used to access properties of an object, but they differ significantly in flexibility and syntax requirements:
| Feature | Dot notation | Bracket notation |
|---|---|---|
| Syntax | obj.key | obj[key] |
| Readability | High | Moderate |
| Variables | NO | YES |
| Special Characters | NO | YES |
| Numbers as Keys | NO | YES |
Using Variables and Expressions
Dot Notation treats the name after the dot as a literal string key. It cannot interpret variables.
Bracket Notation evaluates the expression inside the brackets first, allowing you to pass variables or dynamic strings.
Example
const user = { name: "Alex" };
const choice = "name";
user.choice // undefined (no property named "choice")
user[choice] // "Alex" (evaluates choice to "name")
Special Characters and Spaces
Dot Notation only works with valid JavaScript identifiers (letters, numbers, $, and _, and cannot start with a number).
Bracket Notation accepts any string, making it mandatory for keys with spaces, dashes, or special characters.
Example
const member = {
"user ID": 101,
"land-code": "USA"
};
member.user ID // Syntax Error
member.land-code) // Syntax Error (subtraction)
member["user ID"]) // 101
member["land-code"]) // "USA"
Accessing Arrays with Numbers
Because arrays are objects behind the scenes with numerical indexes, you must use bracket notation to access their values.
Example
// Create an Array
const fruit = ["apple", "banana"];
fruit.0 // Syntax Error
fruit[0] // "apple"
Recommendation
Use Dot Notation by default because it is cleaner and easier to read.
Use Bracket Notation when you need to access properties with variables or when dealing with invalid identifier keys.
Note
In JavaScript, the [ ] symbol serves different purposes depending on how it is used:
- Property Accessor
let name = car["name"] - Array Literal Syntax
const fruits = ["apple", "banana"] - Array Destructuring
const [first, second] = fruits; - Computed Property Names
const obj = {[dynamicKey]: "value"}
Browser Support
[ ] is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera |