Home >Web Front-end >JS Tutorial >Detailed usage of let variables in js and the difference with var

Detailed usage of let variables in js and the difference with var

php是最好的语言
php是最好的语言Original
2018-08-03 09:22:122722browse

I haven’t seen the let variable before, I just encountered it, let’s check it out.

No value assigned after declaration, the performance is the same

(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:

(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);
    }());

Variable scope, different performance:

(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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn