JavaScript: Dot Notation vs Bracket Notation for Accessing Properties

, , …,
Buy 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:

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

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

// the following are syntax errors

x[a b]
// SyntaxError: Unexpected identifier

x."a b"
// SyntaxError: Unexpected string

Example of a property name of digits:

// a property with name that's a digit
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
x."3"
// SyntaxError: Unexpected string

// dot notation cannot be used
x.3
// SyntaxError: Unexpected number

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

// variable in dot notation won't be evaluated

var obj = {"p1":1};
var v = "p2";
obj[v] = 2;
console.log(obj); // { p1: 1, p2: 2 }

obj[v] = 7;
console.log(obj); // { p1: 1, p2: 7 }
blog comments powered by Disqus