JavaScript function declaration ambiguity
Now say the title of this post ten times in a row, five times as fast... yea, anyway. This is meant to be a short and sweet tip about how you declare your functions in JavaScript; mainly because there is a little white lie floating out there that says that the two declarations are synonymous. But one is just shorthand for the other. Here they are represented in code:two supposed synonymous declarations
// regular declaration
function foo() {
// body...
};
// shorthand
var foo = function() {
// body...
};
In reality, nothing is actually wrong with using either style, and they both work. However, there is one very basic situation where the shorthand style won't yield the result you're looking for, and the reason is fairly obvious and simple. Only the first one is an actual function declaration, whereas the shorthand method is just a regular variable declaration with an anonymous function assigned to it as its value. Here is the most basic scenario:
variable defining
var foo = 'bar';
alert(foo); // alerts 'bar'
alert(baz); // alerts 'undefined'
var baz = 'thunk';
The results of this scenario is trivial, but it proves the point. The second alert shows 'undefined' because the variable hasn't been defined yet. Well, the same goes with functions when you're assigning them to a variable. You can't use them, until you've defined them (if you're using shorthand). But with regular function declarations, the JavaScript interpreter knows to fetch the functions when it needs them, even if they aren't declared until further parts in your code. Again, here is a basic scenario;
declaring functions before and after
sayHello(); // alerts 'Hello World'
function sayHello(){
alert('Hello World');
};
sayGoodbye(); // throws error. sayGoodbye is not a function
var sayGoodbye = function() {
alert('Goodbye World');
};
Lesson learned?
Just use regular function declarations all the time? Well, ok, I guess. The obvious use of using variable declaration is that you are indeed assigning 'something' to a variable, and a key takeaway is that you can immediately self-invoke the anonymous function and return a different value back to it. This technique as I've discussed several times on this blog already is known as the modular format which is most commonly used for information hiding. As to why that's important, you'll hear why when my book gets published.
recent
- Matador: The Obvious MVC Framework for Node
- Sandboxing JavaScript
- Crouching Ender, hidden command
- Ender.js - The open submodule library
- Qwery - The Tiny Selector Engine
- Klass
- Smallest DOMReady code, ever.
- $script.js - Another JavaScript loader
- About that slowness on Twitter...
- Autocomplete Fuzzy Matching
- JavaScript Cache Provider
- JavaScript Animate
- Asynchronous method queue chaining in JavaScript
- Something changed
- Unofficial Twitter Widget Documentation
i am dustin diaz

