How does hoisting affect variables and functions?
Asked on Jul 07, 2024
Answer
Hoisting in JavaScript is a behavior where variable and function declarations are moved to the top of their containing scope during the compile phase, but not their initializations. This means you can use functions and variables before they are declared in the code.
<!-- BEGIN COPY / PASTE -->
console.log(myVar); // undefined
var myVar = 5;
console.log(myFunction()); // "Hello, World!"
function myFunction() {
return "Hello, World!";
}
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with JavaScript best practices.- In the example, "myVar" is declared using "var", so it is hoisted to the top of its scope, but its initialization to "5" is not hoisted. Thus, "console.log(myVar);" outputs "undefined".
- The function "myFunction" is fully hoisted, including its body, allowing it to be called before its declaration.
- Variables declared with "let" and "const" are also hoisted but are not initialized, leading to a "Temporal Dead Zone" until the declaration is encountered.
- Always declare variables and functions at the top of their scope to avoid confusion and potential errors.
Recommended Links:
← Back to All Questions