Home > Article > Web Front-end > How to define variables with let and var in js
Both let and var can define variables in js. This article mainly introduces to you the difference between let and var defining variables in js. It is very good and has reference value. Friends who need it can refer to it. I hope it can help everyone.
javascript strict mode
When you first come into contact with the let keyword, there is a concept that you need to pay special attention to, which is "javascript strict mode". For example, the following code will run Error report:
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 to 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 performance is the same
'use strict'; (function() { var varTest; let letTest; console.log(varTest); //输出undefined console.log(letTest); //输出undefined }());
Using undeclared variables, the performance 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 performance 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不是同一个变量 }());
Related recommendations:
Detailed explanation of PHP predefined variables
How to define variables in Javascript?
The above is the detailed content of How to define variables with let and var in js. For more information, please follow other related articles on the PHP Chinese website!