Home  >  Article  >  Web Front-end  >  What is the difference between var and let in javascript

What is the difference between var and let in javascript

青灯夜游
青灯夜游Original
2021-10-13 17:25:2429195browse

Differences: 1. var has variable promotion, but let does not; 2. let does not allow repeated declarations in the same scope, but var does; 3. let does not have a temporary dead zone problem; 4. let The created global variable does not set corresponding attributes for window; 5. let will generate block-level scope, but var will not.

What is the difference between var and let in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

If you want to understand the difference between var (ES5) and let (ES6), you must first understand the variable promotion of JS under ES5

1. Variable promotion (sound)

When the browser opens up the stack memory for code execution, the code is not executed immediately from top to bottom, but continues to do some things: Declare and define all those with var/function keywords in the current scope in advance => Variable promotion mechanism

  • Things with var are only declared in advance var a;, if only declared without assignment, the default value is undefined
    For example:
console.log(a);
var a = 13;

Output: undefined
Equivalent to:

var a;		// 只声明没有赋值,默认为undefined
console.log(a);
a = 13;
  • With function, it is not only declared, but also defined. To be precise, it associates a variable with a certain value.

2. The difference between let and var

1. let and constThere is no variable promotion mechanism

Among the six ways to create variables: var/function has variable promotion, and let/const/class/import This mechanism does not exist

2. <span style="font-size: 18px;">var</span> allows repeated declarations, while <span style="font-size: 18px;">let</span>Duplicate declarations are not allowed

In the same scope (or execution context)

  • If you use the var/function keyword to declare a variable and declare it repeatedly, there will be no impact (after the first declaration, it will not be declared again if it is encountered later)
  • But using let/const will not work. The browser will check whether this variable already exists in the current scope. If it already exists, it will be redeclared again based on let etc. An error will be reported

Before the browser opens up stack memory for top-down execution of the code, there are not only variable promotion operations, but also many other operations => "lexical analysis" or "Lexical detection": It is to detect whether there will be a "SyntaxError" in the code that is about to be executed. If an error occurs, the code will not be executed again (the first line will not be executed)

console.log(1)  // => 这行代码就已经不会执行了
let a = 12
console.log(a)
let a = 13      // => 此行出错:SyntaxError: Identifier &#39;a&#39; has already been declared
console.log(a)

The so-called repetition means: No matter what method was used before, as long as this variable exists in the current stack memory, it is a syntax error if we use let/const to wait for repetition and then declare this variable. eg:

console.log(a)
var a = 12
let a = 13  // => SyntaxError: Identifier &#39;a&#39; has already been declared
console.log(a)
console.log(a)
let a = 13
var a = 12  // => SyntaxError: Identifier &#39;a&#39; has already been declared
console.log(a)

3. let can solve the temporary dead zone problem that occurs during typeof detection (let is more rigorous than var)

console.log(a)
// => ReferenceError: a is not defined

typeof a No error reported

console.log(typeof a)
// =>  &#39;undefined&#39; 这是浏览器的bug,本应报错,因为没有a(暂时性死区)

After using let:

console.log(typeof a)
// => ReferenceError: Cannot access &#39;a&#39; before initialization
let a

returns that it cannot be used before a is defined, temporary solution The problem of sexual dead zone.

4. The global variable created by let does not set the corresponding attribute for window

First look at the global variable created with var or without var The difference

/*
 * What is the difference between var and let in javascript的:相当于给全局对象window设置了一个属性a
 *      window.a = 13
 */
a = 13
console.log(a)  // => window.a 13
/*
 * 栈内存变量存储空间
 *            b
 * What is the difference between var and let in javascript:是在全局作用域下声明了一个变量b(全局变量),
 * 但是在全局下声明的变量也相当于给全局对象window增加了一个对应的
 * 属性b(只有全局作用域具备这个特点)
 */
var b = 14
console.log(b)
console.log(window.b)

What is the difference between var and let in javascript
What is the difference between var and let in javascript
When created using let:

/*
 * 栈内存变量存储空间
 *   c
 * 带let的:仅仅在全局作用域下声明了一个变量b(全局变量),
 * 并未给全局对象window增加对应的属性c
 */
let c = 15
console.log(c)                          // => 15
console.log(window.c)                   // => undefined

What is the difference between var and let in javascript

##5. let will generate a block-level scope

Can the following code change the background color of the body to the color corresponding to the button when a button is clicked? If not, how to improve it (Tencent)

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    html,
    body {
      height: 100%;
      overflow: hidden;
    }

    button {
      padding: 5px 10px;
      cursor: pointer;
    }
  </style>
</head>

<body>
<!---->
<button value="red">红</button>
<button value="green">绿</button>
<button value="blue">蓝</button>

<script>
  var body = document.querySelector(&#39;body&#39;),
    buttons = document.querySelectorAll(&#39;button&#39;),
    arr = [&#39;red&#39;, &#39;green&#39;, &#39;blue&#39;]
  for (var i = 0; i < buttons.length; i++) {
    buttons[i].onclick = function () {
      body.style.background = arr[i]
    }
  }
</script>
</body>

</html>

The answer is of course no, because the variable defined by var, i in the for loop is global, and after the variable is promoted and looped three times, i=3, because clicking each one is equivalent to clicking the last one.

[Recommended learning:

javascript advanced tutorial]

The above is the detailed content of What is the difference between var and let in javascript. 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