Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Object navigation-- when to use object.sub and object["sub"]?

Looking at this from a point of semantics, there's two ways to navigate objects in JS, you can either use the dot operator or work through them like it's a nested array.

When is it appropriate to use one operator over the other? Why shouldn't I just use the method with square brackets all the time (it seems more powerful)? They both seems easy to read, but the dot operator looks like it's limited in that it cannot be provided with variable names of nested objects, or work through arrays.

like image 603
Incognito Avatar asked Jan 05 '11 16:01

Incognito


1 Answers

The main reasons for using []

  1. You can't access properties with the names of keywords via the dot notation (at least not in < ES5)
  2. You can use it to access properties given by a string

The reasons for using .

  1. Always using [] makes syntax highlighting, code completion etc. pretty much useless
  2. Even with automatic insertion of the closing counter parts [' is a hell lot slower to type (especially on non US Keyboard layouts)

I mean, just imagine writing Chat['users']['getList']()['sort']()['each'].

Rule of thumb: Use . where ever possible, and fall back to [] when there's no other way.

like image 77
Ivo Wetzel Avatar answered Sep 28 '22 04:09

Ivo Wetzel