January 12, 2010
Dot vs. Square Bracket Notation in Javascript
I have been looking for an explanation on this for a while. This article summed it right up, Javascript Square Bracket Notation
Javascript also offers an alternative property accessor notation using square brackets in a way that is similar to the way in which the indexed members of an Array are accessed, except that a string is used between the square brackets. This alternative notation is extremely powerful and useful but gets very little coverage in most books on javascript and that seems to leave novice javascript programmers unaware that they even have this option.
Using square bracket notation you can change this:
document.body;
into this:
document['body'];
More importantly though, you can use variables as function names:
var genericString = 'Hello, my name is Ryan.';
var stringMethod = 'split';
genericString[stringMethod](' ');
// returns the array ["Hello,", "my", "name", "is", "Ryan."]