Home > Article > Web Front-end > Detailed usage of let variables in js and the difference with var
I haven’t seen the let variable before, I just encountered it, let’s check it out.
(function() { var varTest; let letTest; console.log(varTest); //输出undefined console.log(letTest); //输出undefined }());
(function() { console.log(varTest); //输出undefined(注意要注释掉下面一行才能运行) console.log(letTest); //直接报错:ReferenceError: letTest is not defined var varTest = 'test var OK.'; let letTest = 'test let OK.'; }());
(function() { "use strict"; var varTest = 'test var OK.'; let letTest = 'test let OK.'; var varTest = 'varTest changed.'; let letTest = 'letTest changed.'; //直接报错:SyntaxError: Identifier 'letTest' has already been declared console.log(varTest); //输出varTest changed.(注意要注释掉上面letTest变量的重复声明才能运行) console.log(letTest); }());
(function() { var varTest = 'test var OK.'; let letTest = 'test let OK.'; { var varTest = 'varTest changed.'; let letTest = 'letTest changed.'; } console.log(varTest); //输出"varTest changed.",内部"{}"中声明的varTest变量覆盖外部的letTest声明 console.log(letTest); //输出"test let OK.",内部"{}"中声明的letTest和外部的letTest不是同一个变量 }());
Remarks:
Use the let statement to declare a variable, and the scope of the variable is limited to the declaration it's in the block. You can assign a value to a variable when you declare it, or you can assign a value to the variable later in the script.
Variables declared using let cannot be used before declaration, otherwise an error will occur.
If your variable is not initialized in a let statement, it will automatically be assigned a JavaScript value undefined
Related articles:
How to define variables with let and var in js
The difference between const, var and let in js
The above is the detailed content of Detailed usage of let variables in js and the difference with var. For more information, please follow other related articles on the PHP Chinese website!