What is the difference between var and let in javascript
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.
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 isundefined
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 const
There 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 onlet
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 'a' 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 'a' has already been declared console.log(a)
console.log(a) let a = 13 var a = 12 // => SyntaxError: Identifier 'a' 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) // => 'undefined' 这是浏览器的bug,本应报错,因为没有a(暂时性死区)
After using let
:
console.log(typeof a) // => ReferenceError: Cannot access 'a' 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)
When created using let:
/* * 栈内存变量存储空间 * c * 带let的:仅仅在全局作用域下声明了一个变量b(全局变量), * 并未给全局对象window增加对应的属性c */ let c = 15 console.log(c) // => 15 console.log(window.c) // => undefined
##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('body'), buttons = document.querySelectorAll('button'), arr = ['red', 'green', 'blue'] for (var i = 0; i < buttons.length; i++) { buttons[i].onclick = function () { body.style.background = arr[i] } } </script> </body> </html>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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 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 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.

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

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

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

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).
