function g () {
var x;
function y () {};
var z;
}
I would like to know exactly what order the above code becomes when hoisted.
Theory 1: Order between var
s and function
s remains as-is:
function g () {
var x;
function y () {};
var z;
}
Theory 2: var
s come before function
s:
function g () {
var x;
var z;
function y () {};
}
Theory 3: function
s come before var
s:
function g () {
function y () {};
var x;
var z;
}
Which theory is correct?
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. Inevitably, this means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.
Hoisting in JavaScript is a behavior in which a function or a variable can be used before declaration. For example, // using test before declaring console.log(test); // undefined var test; Run Code. The above program works and the output will be undefined .
Variables defined with let and const are hoisted to the top of the block, but not initialized. Meaning: The block of code is aware of the variable, but it cannot be used until it has been declared. Using a let variable before it is declared will result in a ReferenceError .
So, why exactly does JavaScript function order matter? Well, function order matters a huge amount when a variety of functions exist inside multiple scopes of a program. For a JavaScript program to perform correctly, functions in the inner scope must be able to access functions in the outer scope.
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);
Both log
calls show the function, not an undefined
value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With