In-depth understanding of let, var and const: What do they mean?
In JavaScript, we have three different ways of declaring variables, namely let, var and const. They have some differences in function and use. Below we will delve into their respective meanings and usage.
Sample code:
function foo() { if (true) { let x = 10; // 只在if块内可见 console.log(x); // 输出10 } console.log(x); // ReferenceError: x is not defined } foo();
Sample code:
function foo() { if (true) { var x = 10; // 函数级作用域,整个函数可见 console.log(x); // 输出10 } console.log(x); // 输出10 } foo();
The variable promotion feature can also be tested within different code blocks:
function foo() { console.log(x); // 输出undefined,而不是ReferenceError: x is not defined if (true) { var x = 10; // 变量提升 } console.log(x); // 输出10 } foo();
Sample code:
function foo() { const PI = 3.14; PI = 3.14159; // TypeError: Assignment to constant variable console.log(PI); } foo();
It should be noted that the constant declared by const means that the value of the variable cannot be changed, not that the object referenced by the variable cannot be changed. If const declares an object, the object's properties can be modified, but cannot be reassigned.
Sample code:
const obj = {x: 10}; obj.x = 20; // 修改属性值 console.log(obj.x); // 输出20 obj = {x: 30}; // TypeError: Assignment to constant variable
Summary:
Different variable declaration methods are suitable for different scenarios. Reasonable selection and use can improve the readability and maintainability of the code. I hope that the introduction in this article can help readers better understand and use let, var and const.
The above is the detailed content of Learn more about let, var, and const: What do they mean?. For more information, please follow other related articles on the PHP Chinese website!