YouTip LogoYouTip

Js Hoisting

# JavaScript Hoisting In JavaScript, the declarations of functions and variables are all "hoisted" to the top of their containing function. In JavaScript, variables can be declared after they have been used. In other words, variables can be used before they are declared. The following two examples will yield the same result: ### Example 1 ```javascript x = 5; // Assign 5 to x elem = document.getElementById("demo"); // Find an element elem.innerHTML = x;// Display x in the element var x; // Declare x [Try it Yourself Β»](#) ### Example 2 ```javascript var x; // Declare x x = 5; // Assign 5 to x elem = document.getElementById("demo"); // Find an element elem.innerHTML = x;// Display x in the element [Try it Yourself Β»](#) To understand the examples above, you need to understand the term "hoisting". Hoisting: Function declarations and variable declarations are always "hoisted" (moved) to the top of their containing function by the interpreter. * * * ## JavaScript Initialization is NOT Hoisted JavaScript initialization is not hoisted. Only the declaration part of a variable is hoisted, not the initialization part. The following two examples yield different results: ### Example 1 ```javascript var x = 5; // Initialize x var y = 7; // Initialize y elem = document.getElementById("demo"); // Find an element elem.innerHTML = x + " " + y;// Display x and y [Try it Yourself Β»](#) ### Example 2 ```javascript var x = 5; // Initialize x elem = document.getElementById("demo"); // Find an element elem.innerHTML = x + " " + y;// Display x and y var y = 7; // Initialize y [Try it Yourself Β»](#) In Example 2, `y` outputs **undefined** because the variable declaration (`var y`) is hoisted, but the initialization (`y = 7`) is not. Therefore, `y` is an undefined variable at that point. Example 2 is equivalent to: ```javascript var x = 5; // Initialize x var y; // Declare y elem = document.getElementById("demo"); // Find an element elem.innerHTML = x + " " + y; // Display x and y y = 7; // Set y to 7 * * * ## Declare Your Variables at the Top Most programmers do not know about JavaScript hoisting. If programmers do not fully understand hoisting, their code can lead to unexpected results. To avoid these issues, it is common practice to declare variables at the beginning of each scope. This is also the normal parsing step in JavaScript and makes the code easier to understand. | ![Image 2: Note](#) | JavaScript strict mode does not allow the use of undeclared variables. In the next chapter, we will learn about **"strict mode"**. | | --- |
← Matplotlib InstallJsref Replaceall β†’