English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In JavaScript, regardless of where they are defined, all variable and function declarations are moved or hoisted to the top of their current scope. This is the default behavior of the JavaScript interpreter and is calledhoisting(提升).
Functions defined using function declarations are automatically hoisted.
This means that they can be called before they are defined.
// Calling a function before its declaration greet(); function greet() { document.getElementById("output").innerHTML = "Hello World"; }Test and see‹/›
As you can see, we have calledgreet()function, but the code is still valid. This is because function declarations are automatically hoisted to the top in the background.
Hoisting is the default behavior of JavaScript where declarations are moved to the top.
JavaScript hoists declarations but not initializations. If a variable is declared and initialized after its use, the value will be undefined.
document.write(num); // undefined var num; num = 50;Test and see‹/›
If a variable is declared after its use and initialized beforehand, it will return this value:
num = 50; document.write(num); // 50 var num;Test and see‹/›
usingletorconstundeclared variables and constants.
JavaScript only hoists declarations, not initializations.
The following two examples produce different results:
var x = 1; // Initialize x var y = 2; // Initialize y document.write(x + " + y()); // 1 2Test and see‹/›
var x = 1; // Initialize x document.write(x + " + y()); // 1 undefined var y = 2; // Initialize yTest and see‹/›
inExample2inOnly the declaration (var y) rather than the initialization (=) 2Hoisted to the top.
Due to hoisting, y has been declared before it is used, but since the initialization has not been hoisted, the value of y is undefined.
The above example is implicitly understood as:
var x; // Declare x var y; // Declare y // Hoisting ends. x = 1; // Initialize x document.write(x + " + y()); // 1 undefined y = 2; // Initialize yTest and see‹/›
Hoisting is an unknown or ignored behavior of JavaScript.
If you do not understand hoisting, the program may contain errors.
To avoid errors, declare all variables at the beginning of each scope.
Note:Under strict mode, JavaScript does not allow the use of variables that are not declared.
You will learn more about "use strict" in the next chapter.