JS: Property Dot Notation / Bracket Notation

By Xah Lee. Date: . Last updated: .

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 that contains space
const x = {"a b": 8};

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

// 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
const x = {"3":8};

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

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


// following are syntax errors
// dot notation cannot be used

x."3"
// SyntaxError: Unexpected string

x.3
// SyntaxError: Unexpected number

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

// creating a property, with name from a value of variable
// dot notation won't work

const obj = {"p1":1};
const v = "p2";

obj[v] = 2;

console.log(obj); // { p1: 1, p2: 2 }

JS Object Property

  1. Property Overview
  2. Property Key
  3. Dot vs Bracket Notation
  4. Create/Delete Property
  5. Get/Set Property
  6. Check Property Existence
  7. Access Property
  8. List Properties
  9. Property Attributes
  10. Getter/Setter
  11. Property Descriptor
  12. Symbol
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc