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

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


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

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
