Table of Contents
1. Variable promotion (sound)
2. The difference between let and var
Home Web Front-end Front-end Q&A What is the difference between var and let in javascript

What is the difference between var and let in javascript

Oct 13, 2021 pm 05:25 PM
javascript let var

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;
Copy after login

Output: undefined
Equivalent to:

var a;		// 只声明没有赋值,默认为undefined
console.log(a);
a = 13;
Copy after login
  • 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)
Copy after login

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)
Copy after login
console.log(a)
let a = 13
var a = 12  // => SyntaxError: Identifier &#39;a&#39; has already been declared
console.log(a)
Copy after login

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
Copy after login

typeof a No error reported

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

After using let:

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

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)
Copy after login

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
Copy after login

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>
Copy after login
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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles