Hoist in JavaScript
Was reading Airbnb style guide for React and get confused when it says
relying on function name inference is discouraged
|
|
Then Googled and found someone mentioned Hoisting in JS.
Just want to write down somthing of what I have learnt from the reading.
So basicly, JS can look ahead of code and find all variable declarations and hosit them to the top of the function.
For example:
The first log didn’t throw an error saying declaredLater
is not defined, instead, it prints undefined
.
This is because of variable hoisting, the above code is actually equivalent to:
For function, hoisting works differently, I’m using some quote cuz i’m lazy :p
However, function definition hoisting only occurs for function declarations, not function expressions. For example:
|
|
Finally, one thing to add-on.
Function’s name doesn’t get hoisted if it is part of a function expression.
|
|
Reference: Variable and Function Hoisting in JavaScript