Just a quick one…
what’s the correct way to format a javascript function?
I see it like this:
function doThis(){
}
and like this:
doThis = function(){
}
Or maybe it make no difference. Please let me know whats best or if they both have different rasons or purposes.
Cheers
C
They are two different things, although they both create a function (and assign it to a variable).
Is a function-statement (or “function declaration”). It is only legal to appear as a top-level script element or directly as an element of a function: that is, it is not legal for a function-statement to appear inside an
if, orwhile, etc. All function statements are “lifted” to the top of the function (or script), thus the following is valid:In the form:
The function keyword is in a function-expression context: it creates a new function-object and the resulting function-object (just a “normal value”) is assigned to
variable. The following is not valid because function-expressions are not lifted.All that being said, the “correct way” is to use the function-statement (“function declaration”) form unless there is reason to do otherwise.
Happy coding.
See also: