javascript tutorial - [Solved-5 Solutions] Var functionName = function() {} vs function functionName() {} - javascript - java script - javascript array
Problem:
Explain Var functionName = function() {} vs function functionName() {} .
Solution 1:
The above actually defines functionThree irrespective of test's value — unless use strict is in effect, in which case it simply raises an error.
Solution 2:
Why no error? We were always taught that expressions are executed from top to bottom(??)
Because:
- Function declarations and variable declarations are always moved
(hoisted)
invisibly to the top of their containing scope by the JavaScript interpreter. Function parameters and language-defined names are, obviously, already there. ben cherry - This means that code like this:
- Notice that the assignment portion of the declarations were not hoisted. Only the name is hoisted.
- But in the case with function declarations, the entire function body will be hoisted as well:
Solution 3:
Solution 4:
An illustration of when to prefer the first method to the second one is when we need to avoid overriding a function's previous definitions.
With
This definition of myfunction will override any previous definition, since it will be done at parse-time.
While
does the correct job of defining myfunction only when condition is met.
Solution 5:
An important reason is to add one and only one variable as the "Root" of your namespace...