Languages
[Edit]
EN

JavaScript - object property access: dot notation vs brackets notation

3 points
Created by:
christa
600

In this article, we would like to show you the difference between dot notation and brackets notation working with object property access in JavaScript.

Simple comparison

Dot notationBrackets notation

Syntax: object.propertyName

Note:

Accessing property this way, in propertyName we must use characters that can be placed in variables.

Syntax: object['propertyName']

Note:

Accessing property this way, propertyName must be a string type.

The most popular way to access the property of an object.Is used when we can't access object property using dot notation.

Practical example:

// ONLINE-RUNNER:browser;

const object = {
  _: 'a',
  $: 'b',
  field: 'c',
  '1': 'd',
  '1.2': 'e',
  '1.2.3' : 'f'
};

// Valid in that notation:

console.log(object._);      // a
console.log(object.$);      // b
console.log(object.field);  // c

// Invalid in that notation:

// console.log(object.1);
// console.log(object.1.2);
// console.log(object.1.2.3);

Practical example:

// ONLINE-RUNNER:browser;

const object = {
  _: 'a',
  $: 'b',
  field: 'c',
  '1': 'd',
  '1.2': 'e',
  '1.2.3' : 'f'
};

// Valid in that notation:

console.log(object['_']);       // a
console.log(object['$']);       // b
console.log(object['field']);   // c

// Still valid in that notation:

console.log(object['1']);       // d
console.log(object['1.2']);     // e
console.log(object['1.2.3']);   // f

Benefits:

Makes code more readable.

Benefits:

Variables can be used to access property values.

 

References

  1. Property accessors - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join