Home Web Front-end HTML Tutorial Detailed explanation of the comparison between const, let and var in JavaScript ES6

Detailed explanation of the comparison between const, let and var in JavaScript ES6

Jun 28, 2017 pm 02:25 PM
const javascript js

This article mainly introduces to you the relevant information on the comparison of const, let and var in JavaScript. The article introduces it in detail through sample code, which has certain reference and learning value for everyone. It is needed Friends, let’s follow the editor and take a look.

ECMAScript 6 New const and let commands are used to declare variables.


Declaration method Variable promotion Scope Initial value Duplicate definition
const No Block level Required No Allow
let No Block level Not required Not allowed
var is function level is not required is allowed

Variable promotion: const and let must be declared before use, variable promotion is not supported


console.log(c1, l1, v1);
// 报错
// Uncaught ReferenceError: c1 is not defined
 
const c1 = 'c1';
let l1 = 'l1';
var v1 = 'v1';
Copy after login


Scope: const, let supports block-level scope, effectively avoiding variable coverage


const c21 = 'c21';
let l21 = 'l21';
var v21 = 'v21';
 
if (0.1 + 0.2 != 0.3) {
 const c21 = 'c22';
 let l21 = 'l22';
 var v21 = 'v22';
 
 console.log(c21, l21, v21);
 // 输出 c22 l22 v22
}
 
console.log(c21, l21, v21);
// 输出 c21 l21 v22
Copy after login


Block-level scope Domain, the outer layer cannot directly access the inner variable


if (0.1 + 0.2 != 0.3) {
 const c22 = 'c22';
 let l22 = 'l22';
 var v22 = 'v22';
 
 console.log(c22, l22, v22);
 // 输出 c22 l22 v22
}
 
console.log(c22, l22, v22);
// 报错
// Uncaught ReferenceError: c22 is not defined
// 同样地, l22 is not defined
Copy after login


const defines constant, which cannot be assigned a value. But the property of this constant can be assigned a value


const c231 = {};
const c232 = [];
 
c231.name = 'seven';
c232.push(27);
 
console.log(c231, c232);
// 输出 {name: "seven"} [27]
 
// 禁止给对象赋值,应该使用 Object.freeze
 
const c233 = Object.freeze({});
const c234 = Object.freeze([]);
 
c233.name = 'seven';
// 普通模式下不报错
// 严格模式下报错
// Uncaught TypeError: Cannot add property name, object is not extensible
  
c234.push(27);
// 普通模式下就会报错
// Uncaught TypeError: Cannot add property 0, object is not extensible
 
console.log(c233, c234);
// 输出 {} []
Copy after login


Global variables are no longer set to the top-level object (window) attributes, effectively avoiding global variable pollution


const c24 = 'c24';
let l24 = 'l24';
 
console.log(c24, l24);
// 输出 c24 l24
 
console.log(window.c24, window.l24);
// 输出 undefined undefined
Copy after login


Conforming to the expected for loop


for (var i = 0; i != 3; i++) {
 setTimeout(function() {
  console.log(i);
 },10);
}
// 依次打印

for (let i = 0; i != 3; i++) {
 setTimeout(function() {
  console.log(i);
 },10);
}
// 依次打印,为啥呢
Copy after login


You can see that using the let method in the for loop to declare variables is in line with expectations.

Every time in the for loop, let redeclares the variable, and because the JavaScript engine will remember the value of the previous loop, initialize i and calculate it based on the previous round.

You can see that there are at least two levels of scope in the for loop. It is easier to understand by looking at the example below.


for (let i = 0; i != 3; i++) {
 let i = 'seven';
 console.log(i);
}
console.log('eight');
// 依次打印
seven
seven
seven
eight
Copy after login


Initial value: const The declared variable must have an initial value set and cannot be assigned repeatedly.


const c3 = 'c3';
let l3 = 'l3';
var v3 = 'v3';
 
console.log(c3, l3, v3);
// 输出 c3 l3 v3
 
c3 = 2; // Uncaught TypeError: Assignment to constant variable
l3 = 2;
v3 = 2;
 
console.log(c3, l3, v3);
// 输出 c3 2 2
 
const c32;
// 报错
// Uncaught SyntaxError: Missing initializer in const declaration
Copy after login


Duplicate definition: const and let do not support repeated definition

const and let reduce the scope of variables. Perfectly avoids variable pollution; const fixed variables (i.e. fixed variable types) can significantly improve performance for weakly typed JavaScript. It is recommended to use const and let to declare variables in your application.

Summarize

The above is the detailed content of Detailed explanation of the comparison between const, let and var in JavaScript ES6. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

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

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

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

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

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

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

See all articles