Skip to content

Bracket notation vs dot notation JavaScript | Basic

  • by

The dot notation and bracket notation both are used to access the object properties in JavaScript. Square bracket notation allows the use of characters that can’t be used with dot notation:

Read more:

var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax

Secondly, square bracket notation is useful when dealing with property names that vary in a predictable way:

for (var i = 0; i < 10; i++) {
  someFunction(myForm["myControlNumber" + i]);
}

The dot notation is used mostly as it is easier to read and comprehend and also less verbose.

Code difference between Bracket notation vs dot notation JavaScript

<!DOCTYPE html>
<html>
<body>
  <script type="text/javascript">

    const obj = {
      name: 'value'
    };

    // Dot Notation
    console.log(obj.name); 


    // Bracket Notation
    console.log(obj['name']); 

  </script>

</body>
</html>

Output:

Bracket notation vs dot notation JavaScript

Smart note:

Accessing members with . is called dot notation. Accessing them with [] is called bracket notation.

  • Dot notation is faster to write and clearer to read.
  • Square bracket notation allows access to properties containing special characters and selection of properties using variables
obj.foo;  // valid
obj.else  // valid, reserved keywords are valid identifier names
obj.42    // invalid, identifier names cannot start with numbers
obj.3foo  // invalid,                ""
obj.foo-bar // invalid, `-` is not allowed in identifier names

obj[42]   // valid, 42 will be coerced to "42"
obj["--"] // valid, any character sequence is allowed
obj[bar]  // valid, will evaluate the variable `bar` and 
          // use its value as property name

Use bracket notation:

  • When the property name is contained in a variable, e.g. obj[foo].
  • The property name contains characters not permitted in identifiers, e.g. starts with a digit, or contains a space or dash (-), e.g. obj["my property"].

Use dot notation: In all other situations.

Source: https://stackoverflow.com

Do comment if you have any doubts or suggestions on this JS notation topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading