Archive for April 21st, 2009

Modern JavaScript Techniques

Tuesday, April 21st, 2009

In my interview with The Thirsty Developer podcast I mentioned some modern JavaScript techniques. It is hard to explain these techniques in a podcast so I wanted to post them here.

Learn more about JavaScript and jQuery at BootWorks, Wednesday, April 22. [ Details ]

The biggest problem area I work to avoid when working with JavaScript is the scoping issue. It has been very common to simply create a series of functions and call them however you see fit from event handlers in your HTML. This was all fine when you had 300 lines of JavaScript for your entire site because it was just used for a slight site enhancement. Now if you are building a much more complex site with lots of interaction, you will have several thousand lines of code. Every one of these functions and variables that you define are all placed in the global scope, which is the window object. Consider the following code.

This code is equivalent to the following code, assuming this code is in the global scope and not within a function block.

Why is this useful? Well, if you are within a function block and declare a variable the scope of that variable is limited to that function block. If you want to declare a variable and put it into the global scope you can use the window object in this way to do so. (Hint: window is the container for the global scope.)

(more...)