Skip to content

Instantly share code, notes, and snippets.

  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save revisualize/2ae6e4d65c56744932f53392eb58518e to your computer and use it in GitHub Desktop.

Accessing values in Objects.

Dot Notation is converting the value to a string (string literal). Example: myObj.name; is the same as myObj["name"]; and as we all know quotes define strings.

If you want to use a variable for accessing the value of object properties you cannot use Dot Notation. You have to use Bracket Notation. Example: var num = 42; myObj[num];

There are a few other limitations when accessing an object property. If the object key has a space or number in it, you cannot use dot notation.

var myObj = {
      "key one": "Value for 'key one'",
      "key": "Value for 'key'",
      "method property": "Method Property would be a function",
      "1": "Value for 'key 1'",
      "2": "Value for 'key 2'"
   };

For ease of explanation, I'm just returning strings for my object property values. The object property keys have a few different aspects to them, a couple with spaces and a couple as numbers.

When you use dot notation to access:

myObj.key one; The object value returned will be a string: "Value for 'key'"

Whereas, when you use bracket notation and access an object property key:

myObj["key one"]; The object value returned will be a string "Value for 'key one'".

If you try to use dot notation to access an object property with a space in it that doesn't have an additional corresponding shorter object property key. (Like I did with "key one" and "key")

You'll get the error: Uncaught SyntaxError: Unexpected identifier or SyntaxError: Unexpected token, expected ;

If you attempt to just do myObj.method; you will get back the value undefined

Additionally, if you were to access a number with dot notation:

myObj.1; .. You will get an error: Uncaught SyntaxError: Unexpected number or you may get SyntaxError: Unexpected token, expected ;

If you want to access an object property with a number as the object key you will be required to use Bracket Notation:

myObj["1"]; and you will get the object property value of "Value for 'key 1'".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment