JavaScript: Dot Notation vs Bracket Notation for Accessing Properties

, , …,
Want to master JavaScript in a week? Example based, to the point. Xah JavaScript Tutorial.

There are 2 syntax to access a object's property:

They are equivalent, except:

Example of a property name with space in it:

// creating object with property name containing a space
var x = {"a b": 8};

console.log(x["a b"]);          // 8

// dot notation cannot be used
console.log( x."a b" );         // SyntaxError: Unexpected string

Example of a property name that's a digit or number-like:

// creating object with property name that's number-like
var x = {"3":8};

console.log(x["3"]);            // 8

console.log(x[3]);   // 8 JavaScript automatically convert 3 to string

// dot notation cannot be used
console.log( x."3" );           // SyntaxError: Unexpected string

// dot notation cannot be used
console.log( x.3 );             // SyntaxError: Unexpected number

Here's a example of creating property with a name from the value of a variable.

// dot notation for properties can't be variables

// creating object
var x = {"one":1};

var v = "two";

// create a property using name from variable
x[v] = 2;  // same as x["two"] = 2

console.log(x);                 // { one: 1, two: 2 }

x.v = 333; // WRONG. It'll create a property named v instead

console.log(x);                 // { one: 1, two: 2, v: 333 }

Property Names Are Strings

JavaScript: Property Names Are Strings

blog comments powered by Disqus