Home > Article > Web Front-end > What is JavaScript Hoisting?
Hoisting is a mechanism in JavaScript that moves the declaration of variables and functions to the top; allowing us to use variables and functions before declaring them, that is: allowing variables and functions to be used first and then declared. .
This article will introduce to you the hoisting mechanism (Hoisting) of JavaScript and let you understand JS variable hoisting and function hoisting. I hope it will be helpful to you.
JavaScript's hoisting mechanism (Hoisting) only applies to declarations rather than initialization; we need to initialize and assign variables and function values before using them. [Related video tutorial recommendations: JavaScript Tutorial]
JavaScript variable promotion
Let’s take a look at the simplicity of variable promotion example.
//先使用变量 x x = "php中文网"; // 初始化变量 x,赋值为"php中文网" alert("变量x的值为:"+x); //弹窗显示 x(使用x) //后声明变量 x var x; // 变量 x的声明
This is the same as the following example of declaring variables first and then using them.
var x; // 声明 变量 x x = "php中文网"; // 初始化变量 x,赋值为"php中文网" alert("变量x的值为:"+x); //弹窗显示 x(使用x)
Output result:
Note: cannot be initialized directly when the variable is declared. Example:
var x="php中文网";
This cannot be improved. Let’s look at two examples:
Example 1:
var x = "php中文网"; // 声明,初始化变量 x,赋值为"php中文网" var y = "网址为:www.php.cn"; // 声明,初始化变量 x,赋值为"php中文网" alert(x+"\n"+y); //弹窗显示 x(使用x)
Output:
Example 2:
var x = "php中文网"; // 声明,初始化变量 x,赋值为"php中文网" alert(x+"\n"+y); //弹窗显示 x(使用x) var y = "网址为:www.php.cn"; // 声明,初始化变量 x,赋值为"php中文网"
Output:
JavaScript function Hoisting
Let’s look at a simple example of variable hoisting.
//先使用函数 sum() alert("\nsum()的作用是:让两个数相加求和,则:\n\n"+"sum(10,20)=10+20="+sum(10,20)); //在声明函数sum() function sum(a,b) { return a+b; }
This is the same as declaring the function sum() first and then using it. The output result is the same:
//在声明函数sum() function sum(a,b) { return a+b; } //输出函数 sum() alert("\nsum()的作用是:让两个数相加求和,则:\n\n"+"sum(10,20)=10+20="+sum(10,20));
Rendering:
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
The above is the detailed content of What is JavaScript Hoisting?. For more information, please follow other related articles on the PHP Chinese website!