Order of hoisting in JavaScript
Functions are hoisted first, then variable declarations, per ECMAScript 5, section 10.5 which specifies how hoisting happens:
We first have step 5 handling function declarations:
For each FunctionDeclaration f in code, in source text order do...
Then step 8 handles var
declarations:
For each VariableDeclaration and VariableDeclarationNoIn d in code, in source text order do...
So, functions are given higher priority than var
statements, since the later var
statements cannot overwrite a previously-handled function declaration.
(Substep 8c enforces the condition "If varAlreadyDeclared is false, then [continue...]" so extant variable bindings are not overwritten.)
You can also see this experimentally:
function f(){}var f;console.log(f);
var g;function g(){}console.log(g);
Hoisting order of precedence and variable mutation
(From the comments)
If variable assignment takes precedence over function declaration why isn't
double = 22
above the function declaration?
Variable name declarations are hoisted, but assignments (=
) are never hoisted.
Then what does "Variable assignment takes precedence over function declaration" mean?
It makes no sense at all, really. An assignment and a declaration are two totally unrelated things, they don't "take precedence" over each other. I guess it's supposed to mean just that you can always assign a mutable variable, and it will hold the assigned value afterwards, regardless of where/how the variable was declared (with var or function).
How in my last example even though function is hoisted above the variable declaration the output is still function instead of undefined?
Because "takes precedence" doesn't refer to order, as in "is hoisted above the other". Declarations don't really have any order for our purposes, all variables are created at once (that's what "hoisting" actually means).
The precedence refers to the value that the variable is initialised with, undefined
for var
s and function objects for function
s. The rule means that when there is a function
declaration with the same name as a var
declaration, then the variable is initialised with the function.
javascript hoisting: what would be hoisted first — variable or function?
Given var foo = something
, only the variable declaration is hoisted.
This means that var foo
is hoisted but the foo = something
will run in the reading order.
Given function foo() {}
, the variable declaration and function assignment are both hoisted. This creates the variable foo
and gives it the value of the function.
If you have both of the above, then you declare the variable twice (for no extra effect) and assign it the value of the function (as that is the only assignment).
So in your second example…
The function declaration is hoisted, so f(); // - first f
calls that.
The assignment of the function expression is not hoisted, but f(); // ** - second f
appears after it in normal reading order, so the second call to foo()
hits that.
Hoisting order with IIFE involved, specific example
- The IIFE is an expression, not a statement, so no it is not hoisted.
var myVar
inside the IIFE is hoisted to the top of the function scope, but the assignment is not. The following is equivalent:
(function(){ var myVar; console.log('Original value was: '+ myVar); myVar = 'bar'; console.log('New value is: ' + myVar);})();
how hoisting works ? difference between function and variable
It doesn`t return number 12 because hoisting works only for declarating the actual variable, not to assign it a value.
This means that your code looks like this for compilator:
function scope() {
var hosting;
return hosting;
hosting=12;
}
Also please remember that everything after return
is not executed.
Confusion about Javascript Hoisting
The reason why var example = function()
is getting called instead of function example()
is the order of hoisting.
Functions are hoisted first, then variable declarations, per
ECMAScript 5, section 10.5 which specifies how hoisting happens.
Read more here: Order of hoisting in JavaScript
Is there any benefit from hoisting?
The main benefit of hoisting is that functions don't have to be declared in a specific order in order to work properly. The interpreter makes a pass over a function of code and finds all the function declarations within that function and makes them available to code anywhere in the scope (hoisting them) whether the code referring to the functions is before or after where the function declarations are located. It also allows A to call B and B to call A without running into declaration ordering issues.
Variable hoisting is rarely used anymore now that we have const
and let
which are block scoped and cannot be used before declaration. So hoisting is mainly useful for function declarations now.
Related Topics
Why Were Es5 Object Methods Not Added to Object.Prototype
How to Parse a Url Query Parameters, in JavaScript
Three.Js:2Xmeshes Using Same Vector as Position
A Proper Wrapper for Console.Log with Correct Line Number
How to Set the Prototype of a JavaScript Object That Has Already Been Instantiated
Convert Time Interval Given in Seconds into More Human Readable Form
Firebase Query Methods Startat() Taking Case Sensitive Parameters
Normalizing Mousewheel Speed Across Browsers
JavaScript to Sort Contents of Select Element
Incorrect Result in JavaScript Calculation
Generate HTML Table from 2D JavaScript Array
Javascript: Get Argument Value and Name of Passed Variable
Dc.Js - How to Create a Row Chart from Multiple Columns
Multiple Path Names for a Same Component in React Router
Node.Js: Read a Text File into an Array. (Each Line an Item in the Array.)