In Javascript, I have seen three different ways to define a function.
function foo()
{
//do something
}
var foo = function(){
//do something
}
window.foo = function(){
//do something
}
What question is,
What is the difference between the above three? And which one should I be using & why?
The first one is function declaration. It is hoisted (you could use it anywhere inside current scope).
The second one is a variable definition using anonymous function. Variable is hoisted, assignment stays in place. The function may not be used until the line where you assign it.
The third one is assigning a global method. Similar to the second one, although works with global object, which is not good.
Yet, you could think about the fourth alternative(named function expression):
var foo = function bar(){ //do something }
Here, bar will be available only inside itself, which is useful for recursion and not churning current scope with it.
You are selecting any approach based on your needs. I'd only vote against the second approach, as it makes function behave like a variable.
As soon as you mention both the second and the third option, I'd like to remind that polluting global object is considered bad practice. You'd better think about using self-executing anonymous functions to create separate scope, e.g.
(function(){
var t = 42; // window.t still does not exist after that
})();
I suppose you may find a more detailed article on JavaScript Scoping and Hoisting useful.
First, see Javascript: var functionName = function() {} vs function functionName() {}.
Then we get to the difference between var foo =
and window.foo =
.
The first is a locally scoped variable which is nice and lovely (unless it is done in the global scope). The second is a an explicit global, which has all the usual issues of globals (such as likelihood of conflicting with other code).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With