Ben Cherry, a former Twitter engineer, writes about JavaScript patterns, scoping and hoisting, modules, and testable code.
Commenters cite his scoping and hoisting and module pattern posts as clear JavaScript explainers; he says blogging helped him land his Twitter job.
I can take a stab at it.
All variables are hoisted to the top of a function, where they are defined as 'undefined'. This is confusing, I know - there is actually a difference between an undefined variable (accessing it will cause a ReferenceError) and a variable defined as 'undefined', which is in many cases identical to null, except in object syntax.
An example you can run in your inspector:
function foo(){
console.log(a);
var a = "string";
}
function bar(){
console.log(a);
}
foo(); // logs 'undefined'
bar(); // throws ReferenceError
Why does this happen?
Well, this is because of the variable hoisting. Before running a function, the interpreter scans for any var definitions and 'hoists' them to the top of the function, where they are set to undefined. This leads to the strange situation where defining a variable after it's been accessed (as in foo()) actually prevents an exception.
The same is true of functions defined with the 'function name(){}' syntax. As opposed to the 'var name = function(){}' syntax, the entire function (including the definition of the function!) is hoisted to the top of the containing function. So this will work:
function foo(){
bar();
function bar(){
console.log("works!");
}
}
foo();
This can be confusing but if used properly can be very helpful in refactoring your code. For instance, there are times when I've easily cleaned up code by just putting them into separate function definitions within…
So say 50 elements. With a 50ms difference that's 2.5 seconds of total time. Most browsers will do 2-4 simultaneous connections, so let's say 4, that's still over 1/2 second faster page load. Now put that end user in Europe or Africa, and you're looking at 200-500 ms latency per call, versus 10 ms. You can see how the math works.
Assets loaded on some of your recently submitted URLs:
21 - http://www.mozilla.org/en-US/firefox/10.0/releasenotes/
60 - http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
104 - http://www.hollywoodreporter.com/thr-esq/falling-skies-lawsuit-tnt-font-285103
282 - https://plus.google.com/u/0/111314089359991626869/posts/HQJxDRiwAWq
54 - http://www.computerworld.com/s/article/9223601/Anonymous_dupes_users_into_joining_Megaupload_attack
67 - http://abcnews.go.com/blogs/politics/2012/01/rand-paul-in-pat-down-standoff-with-tsa-in-nashville/
70 - http://www.wptavern.com/bad-behavior-in-the-wordpress-community
etc....
The impact of reducing latency for each of those calls, and offloading those requests from your server(s) is a big deal for big sites.
(I'm the author.)
JavaScript can be pretty overwhelming to newcomers. You mention scope, which is a good example of where CoffeeScript actually clarifies rather than hides the underlying semantics.
The most important thing to understand about scope in JS is that only functions create scope. This is very different from C and Java, and since JavaScript looks like C and Java, that difference is surprising (see e.g. http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting). When you learn the same rule in CoffeeScript, it feels a lot simpler. And that understanding can carry over to JS.
Granted, the compiler is generating the `var` keyword for you, but the mapping is trivial. What's important is that scoped variables have the same behavior in both languages.
I learned this method with the book JavaScript the Good Parts, though it was a while ago and I can't remember the specific reasoning behind the books' recommendation.
From the other commenter's SO link, I found this link to go more in depth into the differences of declaring functions, and it seems to come down to having stricter control on the order of events with no surprises.
http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
And here's an example of one of the surprises you'll run into if you don't declare your functions in this way:
http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
I've been trying to come up with a javascript module pattern for my rails apps. Right now, I use the Foundations javascript libraries, however those are very generic. I'd like to do something like Foundation does: have separate js files for accordians, sliders, tooltips, etc...I've been looking at the module patterns, however, as a new-comer to js (I'm ruby backend dev), there seems to be so many ways (http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth), to do the same thing, and I'm at a loss trying to figure out which one to start out with.
Anyone facing this issue? How have you gone about starting out? Thanks.
I tend to do the same thing. Except, since JavaScript doesn't have block scope, it all ends up at the top of the function.
Which is much more preferable than scattered around the function. Especially due to hoisting[1].
My functions typically go in the order of:
declare variables;
declare any local functions if necessary (most of the time these eventually get refactored out to somewhere else, because they tend to be one-off utility functions that can be abstracted);
do stuff;
return value.
1. http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting