I know that there are several ways to define a function in JavaScript. Two of the most common ones are:
(1) function add (a, b) {
return a + b;
}
(2) var add = function (a, b) {
return a + b;
}
I am comfortable with the idea of a function as an object that can be passed around just like any other variable. So I understand perfectly what (2) is doing. It’s creating a function and assigning to add (let’s say this is in the global scope, so add is a global variable) the said function. But then what is happening if I use (1) instead? I already know that it makes a difference in execution order: if I use (1) then I can refer to add() before the point in the code where add() is defined, but if I use (2) then I have to assign my function to add before I can start referring to add().
Is (1) just a shortcut for (2), albeit one that happens to behave like other C-style languages in allowing us to define a function “below” the point at which it’s used? Or is it internally a different type of function? Which is more “in the spirit” of JavaScript (if that isn’t too vague a term)? Would you restrict yourself to one or the other, and if so which one?
It looks like you are already aware of the main characteristics of function declarations1 (1) and function expressions (2). Also note that in (1) there is still a local variable called
addcontaining a function value, just like in (2):One other point worth mentioning is that function declarations (1) shouldn’t be used to define functions conditionally (such as in
ifstatements), because as you have mentioned, they are automatically moved to the top of the containing scope by the JavaScript interpreter2. This is normally referred to as hoisting.As for which approach is more in the spirit of JavaScript, I prefer using function expressions (2). For a more authoritative opinion, Douglas Crockford lists function declarations (1) in the “Bad Parts” chapter in his popular The Good Parts book2.
1 Also known as function statements (See @Tim Down’s comments below).
2 Actually some browsers are able to handle function declarations in
ifstatements (Again refer to comments below).3 JavaScript: The Good Parts – Appendix B: Page 113.