This article mainly introduces the difference between let and var defined variables in js. It is very good and has reference value. Friends in need can refer to it
javascript strict mode
This is the first time I come across the let keyword. One concept that needs to be very, very important to pay attention to is "javascript strict mode". For example, if the following code is run, an error will be reported:
let hello = 'hello world.'; console.log(hello);
The error message is as follows:
let hello = 'hello world.'; ^^^ SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode ...
The solution is to add the "javascript strict mode" statement in the file header:
'use strict'; let hello = 'hello world.'; console.log(hello);
Similarities and differences between let and var keywords
No value assigned after declaration, the behavior is the same
'use strict'; (function() { var varTest; let letTest; console.log(varTest); //输出undefined console.log(letTest); //输出undefined }());
Using undeclared variables, the behavior is different:
(function() { console.log(varTest); //输出undefined(注意要注释掉下面一行才能运行) console.log(letTest); //直接报错:ReferenceError: letTest is not defined var varTest = 'test var OK.'; let letTest = 'test let OK.'; }());
When the same variable is declared repeatedly, the behavior is different:
'use strict'; (function() { 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); }());
Variable scope, different performances
'use strict'; (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不是同一个变量 }());
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Detailed explanation of introducing elementUI components into the vue project
How to implement setting as a separate page in Vue-cli Background color
Refresh and tab switching in vue
The above is the detailed content of What are the differences between let and var defined variables in js?. For more information, please follow other related articles on the PHP Chinese website!