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?