I'm still awaiting my copy of Javascript Patterns, hopefully it'll arrive today so I have some weekend reading. In the meantime I thought I would post about a technique of property/method access that not everyone will know about.
Accessing a method in javascript is not a complicated operation, usually you just do <object>.<method>(). Nothing hard there. But this can sometimes lead to somewhat more verbose code that we'd like, for example say we wanted to add or remove a class using jQuery based on a boolean value.
if(myBool)
myElement.addClass("Active");
else
myElement.removeClass("Active");
Sure I can store the class name in a variable and not repeat that, but it'd still leave us with a multiline statement. Fortunately we can compress this down to a single line of code. In javascript we can access object property and methods by using array brackets but providing a string key for the property or method name, e.g. <object>["Method"](); Its important to note the method name is in a string, if you don't provide it as a string then it will not work as expected and probably error. Programmers of C# and similar languages will be familiar with this syntax for accessing Dictionaries and similar structures.
So how can we use this to improve the code above? Well as we're providing the method name as a string to the "[]", we can simply control what string is placed within it.
myElement[(myBool ? "add" : "remove") + "Class"]("Active");
Now in the above statement we use a ternary statement to decide if we prefix "Class" with add or remove. This determines in turn which property or method you call. Some may argue (and indeed do at my work) that this has an impact on readability, but I personally think its worth the hit in terms of concise code. Knowing about this method of accessing properties and methods can help you write code that takes advantage of this feature, leading to much less repetition of code.