Differences between let and var variables defined in js, jsletvar Variables
Strict javascript Mode
The first touch with the let keyword has a very important concept that is "javascript strict mode". For example, if the following code is run, an error is 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, same performance
'Use strict '; (function () {var varTest; let letTest; console. log (varTest); // output undefined console. log (letTest); // output undefined }());
Using undeclared variables is different:
(Function () {console. log (varTest); // output undefined (note that you need to comment out the following line before running) console. log (letTest); // the following error occurs: ReferenceError: letTest is not defined var varTest = 'test var OK. '; let letTest = 'test let OK. ';}());
Repeated declarations of the same variable are different:
'Use strict '; (function () {var varTest = 'test var OK. '; let letTest = 'test let OK. '; var varTest = 'vartest changed. '; let letTest = 'lettest changed. '; // directly reports the following error: SyntaxError: Identifier 'lettest' has already been declared console. log (varTest); // output varTest changed. (note that you need to comment out the repeated declaration of the letTest variable above before running) console. log (letTest );}());
Variable scope, different performance
'Use strict '; (function () {var varTest = 'test var OK. '; let letTest = 'test let OK. '; {var varTest = 'vartest changed. '; let letTest = 'lettest changed. ';} console. log (varTest); // output "varTest changed. ", the varTest variable declared in the internal" {} "overwrites the external letTest declaration console. log (letTest); // output "test let OK. ", the letTest declared in the internal" {} "is not the same variable as the external letTest }());
Summary
The above section describes the differences between let and var variables in Javascript. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!