To var, or not to var
Or you can declare it without a var in your statement:
I recently read an accepted answer on Stack Overflow that stated:
“If you’re in the global scope then there’s no difference.“
I’m sorry but I don’t agree. If that statement was correct, then I would get the same result for this:
As you can see, attempting to call func1 before it has been declared throws an error, whereas func2 is able to be called successfully. This means that there is a difference and it’s nothing to do with scoping, either locally or globally:
- func1 (var format) is defined at runtime
- func2 is defined before runtime, they’re “hoisted“
I refer to the first (with var) declaration as a function expression. func1 is actually an anonymous function expression, the variable that is assigned the function has a name, func1 but the function itself doesn’t. To give the function itself a name, you could do:
Function expressions are more versatile, if you create a new function with currying or Multiple Function Composition you’re using a function expression. Function expressions go hand in hand with functional programming. Personally, I always define my functions as an expression (the first way, using a var), therefore it must be best practice :)
If you’re a CoffeeScripter, get off my blog ;). Also, there’s only one way you can define a function in coffeescript:
Which is evaluated as a function expression, fortunately.
Now seriously, get off my blog CoffeeScripters.