Explain Codes LogoExplain Codes Logo

Javascript property access: dot notation vs. brackets?

javascript
prompt-engineering
functions
callbacks
Nikita BarsukovbyNikita Barsukov·Nov 4, 2024
TLDR

Easily access object properties in JavaScript by using dot notation (object.property) for static and valid names. For dynamic or special-character names, employ bracket notation (object['property']). Consider the following example:

let obj = { a: 1, 'b c': 2 }; console.log(obj.a); // dot: valid identifier console.log(obj['b c']); // brackets: because spaces aren't chill with dot notation

Understanding when to apply dot notation and bracket notation isn’t about just knowing your options. It’s about how you choose to uphold your coding style and the specific demands of the code you've to write.

Working within property name rules

Skirting around reserved keywords

With dot notation, using reserved keywords can lead to syntax errors:

let obj = { class: 'A' }; // Syntax error: class can't sit with us

In these cases, bracket notation provides a loophole:

let obj = { 'class': 'A' }; console.log(obj['class']); // No error: class can sit with us inside brackets

Dealing with numeric keys

Have numeric keys? Dot notation is a bit picky in these scenarios:

let arrayLikeObj = { 0 : 'a', 1 : 'b'}; console.log(arrayLikeObj.0); // SyntaxError: dot notation didn't sign up for numbers

But bracket notation saves the day:

console.log(arrayLikeObj[0]); // Prints 'a', because brackets are all-inclusive

Handling dynamic property names and expression execution

Variables as keys

When you're dealing with property names that change on the fly, bracket notation rise and shines:

let propName = 'username'; let user = { [propName]: 'Alex123' }; console.log(user.username); // 'Alex123' - bracket notation, your variable whisperer

Leveraging expressions within properties

Moreover, bracket notation gives you the freedom to use complex expressions:

let suffix = 'name'; console.log(user['user' + suffix]); // 'Alex123', concat and access like a pro

Incorporating special characters and spaces

Dot notation won't cooperate with special characters or spaces in property names. However, brackets make it possible:

let weirdObj = { 'hello-world': true, 'data-123': 'xyz' }; console.log(weirdObj['hello-world']); // true, brackets letting it loose!

Accounting for code generators and edge cases

Script generators and dynamic code

In code generators or tools that automate code writeups, the versatility and broader compatibility of bracket notation come in handy.

Legacy code and the IE8 caveat

Working with legacy code, especially for IE8? It's those times when dot notation doesn't work well with reserved keywords:

let oldIEObject = { 'class': 'old-school', 'default': 'value' // 'default' is a reserved keyword }; // IE8 workaround: console.log(oldIEObject['class']); // Brackets for the win, for old times' sake console.log(oldIEObject['default']);

Balancing readability and accessibility

Bracket notation might need more work to write, but it guarantees accessibility under uncertain conditions.

Knowing a property name and ensuring it's a valid identifier allows you to uphold the readability of your code with dot notation:

let car = { make: 'Ford', model: 'Mustang' }; console.log(car.make); // Clean and clear like a Spring morning

On the other hand, the bracket version could be less intuitive:

console.log(car['model']); // Correct but feels like reading a novel backwards

Useful scenarios for each notation

Accessing array elements

Use bracket notation when you're working with array elements, especially handling dynamic indices:

let colors = ['red', 'green', 'blue']; let index = 2; console.log(colors[index]); // 'blue', because indexes are dynamic like your mood

Traversing properties

While iterating properties, utilizing variables to access them necessitates brackets:

for (let key in obj) { console.log(obj[key]); // walk through each property like a morning stroll }

Parsing JSON

When JSON parsing, property names behave like strings, making bracket notation commonplace:

let jsonData = '{"name": "John", "age": 31}'; let parsedData = JSON.parse(jsonData); console.log(parsedData['age']); // 31, because JSON demands a bracket pass