- use function statement,
- use function expression
Function statement:
Function expression:
The above two have the exactly same result. they will both define a function foo. But I found there are still one difference: scope.
The function statement is globally scoped, it can be put anywhere in the javascript, and you can call the function before or after it is defined.
For example:
But in function expression is different, the function call statement must be after the function is defined, otherwise the function call will be failed.
For example:
When you think a little deeper, the error of function expression make sense, because the function expression means first declare a variable, then assign it with a function object. Why it failed before the function defined is because the variable is not declared and assigned yet.
So if you use the function expression to define a javascript function, you need to aware this issue.
GOOD POST! but I would like to append the fundamental reason why this is happening. It's because variable hoist. check it out!
ReplyDelete