Suggest an editImprove this articleRefine the answer for “Bracket notation”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)In JavaScript, object properties can be accessed with **bracket notation** (`object['key']`), passing a string or a variable holding the property name instead of `'key'`. **Key point:** bracket notation is required when the key is a dynamic value stored in a variable, contains spaces, a hyphen, a leading digit or a special character, or is computed by an expression.Shown above the full answer for quick recall.Answer (EN)ImageIn 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 `[]` | Situation | Why | |---|---| | 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 expression | `obj['prefix_' + id]` | --- ## Summary | Way | Example | When to use | |---|---|---| | Dot notation | `user.name` | when the key is known in advance and is a valid identifier | | Bracket notation | `user['name']` or `user[key]` | when the key is dynamic or contains special characters |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.