


What are the differences between variable declaration var and let.const?
This time I will bring you the differences between the use of variable declaration var and let.const. What are the precautions when using variable declaration var and let.const. The following is a practical case. Let’s take a look. .
var declarationThe scope of the variableRestricted to the context of its declaration position
var x = 0; // x是全局变量,并且赋值为0。 console.log(typeof z); // undefined,因为z还不存在。 function a() { // 当a被调用时, var y = 2; // y被声明成函数a作用域的变量,然后赋值成2。 console.log(x, y); // 0 2 function b() { // 当b被调用时, x = 3; // 全局变量x被赋值为3,不生成全局变量。 y = 4; // 已存在的外部函数的y变量被赋值为4,不生成新的全局变量。 z = 5; // 创建新的全局变量z,并且给z赋值为5。 } // (在严格模式下(strict mode)抛出ReferenceError) b(); // 调用b时创建了全局变量z。 console.log(x, y, z); // 3 4 5 } a(); // 调用a时同时调用了b。 console.log(x, z); // 3 5 console.log(typeof y); // undefined,因为y是a函数的本地(local)变量。
letThe variable declared is only available in the block or subblock in which it is declared, var The scope of is the entire enclosing function
function varTest() { var x = 1; if (true) { var x = 2; // 同样的变量! console.log(x); // 2 } console.log(x); // 2 } function letTest() { let x = 1; if (true) { let x = 2; // 不同的变量 console.log(x); // 2 } console.log(x); // 1 }
In ECMAScript 2015, let bindings are not subject to variable hoisting, which means that let declarations are not hoisted to the top of the current execution context.
Before the variable in the block is initialized, referencing it will cause a ReferenceError (the opposite is true when using var to declare a variable, the value of the variable is undefined)
When used in a block, let will change the scope of the variable Limited to this block. Note that the scope of var is within the function in which it is declared.
var a = 1; var b = 2; if (a === 1) { var a = 11; // the scope is global let b = 22; // the scope is inside the if-block console.log(a); // 11 console.log(b); // 22 } console.log(a); // 11 console.log(b); // 2
const A constant must specify its value at the time of declaration. The
const declaration creates a read-only reference to the value. But this does not mean that the value it holds is immutable (such as the reference content is an object), but the variable identifier cannot be reassigned. A constant cannot have the same name as other variables or functions in its scope
// 注意: 常量在声明的时候可以使用大小写,但通常情况下全部用大写字母。 // 定义常量MY_FAV并赋值7 const MY_FAV = 7; // 报错 MY_FAV = 20; // 输出 7 console.log("my favorite number is: " + MY_FAV); // 尝试重新声明会报错 const MY_FAV = 20; // MY_FAV 保留给上面的常量,这个操作会失败 var MY_FAV = 20; // 也会报错 let MY_FAV = 20; // 注意块范围的性质很重要 if (MY_FAV === 7) { // 没问题,并且创建了一个块作用域变量 MY_FAV // (works equally well with let to declare a block scoped non const variable) let MY_FAV = 20; // MY_FAV 现在为 20 console.log('my favorite number is ' + MY_FAV); // 这被提升到全局上下文并引发错误 var MY_FAV = 20; } // MY_FAV 依旧为7 console.log("my favorite number is " + MY_FAV); // 常量要求一个初始值 const FOO; // SyntaxError: missing = in const declaration // 常量可以定义成对象 const MY_OBJECT = {"key": "value"}; // 重写对象和上面一样会失败 MY_OBJECT = {"OTHER_KEY": "value"}; // 对象属性并不在保护的范围内,下面这个声明会成功执行 MY_OBJECT.key = "otherValue"; // 也可以用来定义数组 const MY_ARRAY = []; // It's possible to push items into the array // 可以向数组填充数据 MY_ARRAY.push('A'); // ["A"] // 但是,将一个新数组赋给变量会引发错误 MY_ARRAY = ['B']
The following introduces the three ways to declare variables in javascript: var, let, const.
var declares global variables. In other words, the variables declared in for loop can also be used when jumping out of the for loop.
for(var i=0;i<=1000;i++){ var sum=0; sum+=i; } alert(sum);
The sum declared inside the for loop can be used when jumping out of the for loop, and the result will pop up normally without error.
let: Declare block-level variables, that is, local variables.
In the above example, if you jump out of the for loop and use the sum variable again, an error will be reported. It has a strict scope. The variable only scopes the code block it currently belongs to. The same variable cannot be defined repeatedly and cannot be declared in When called before, it must be defined before use, and an error will be reported. You can use let
in the loop body. Note: you must declare 'use strict'; before you can use let to declare variables, otherwise the results will not be displayed when browsing,
const: used to declare constants, also has block-level scope, and can also be declared at block level.
const PI=3.14;
It is the same as let, and the same variable cannot be defined repeatedly. Once const is defined, it cannot be modified.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to use vue calculated properties and method listeners
How to declare JS variables var, let.const
The above is the detailed content of What are the differences between variable declaration var and let.const?. 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



Magnet link is a link method for downloading resources, which is more convenient and efficient than traditional download methods. Magnet links allow you to download resources in a peer-to-peer manner without relying on an intermediary server. This article will introduce how to use magnet links and what to pay attention to. 1. What is a magnet link? A magnet link is a download method based on the P2P (Peer-to-Peer) protocol. Through magnet links, users can directly connect to the publisher of the resource to complete resource sharing and downloading. Compared with traditional downloading methods, magnetic

How to use mdf files and mds files With the continuous advancement of computer technology, we can store and share data in a variety of ways. In the field of digital media, we often encounter some special file formats. In this article, we will discuss a common file format - mdf and mds files, and introduce how to use them. First, we need to understand the meaning of mdf files and mds files. mdf is the extension of the CD/DVD image file, and the mds file is the metadata file of the mdf file.

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

After long pressing the play button of the speaker, connect to wifi in the software and you can use it. Tutorial Applicable Model: Xiaomi 12 System: EMUI11.0 Version: Xiaoai Classmate 2.4.21 Analysis 1 First find the play button of the speaker, and press and hold to enter the network distribution mode. 2 Log in to your Xiaomi account in the Xiaoai Speaker software on your phone and click to add a new Xiaoai Speaker. 3. After entering the name and password of the wifi, you can call Xiao Ai to use it. Supplement: What functions does Xiaoai Speaker have? 1 Xiaoai Speaker has system functions, social functions, entertainment functions, knowledge functions, life functions, smart home, and training plans. Summary/Notes: The Xiao Ai App must be installed on your mobile phone in advance for easy connection and use.
