This article mainly shares with you the declared variables let and const of the ES6 series. Interested friends can refer to the content in this article
Introduction
Concept
The first version of ES6 was released in June 2015, and its official name is "ECMAScript 2015 Standard" (ES2015 for short). ES6 is both a historical term and a general term. It means the next generation standard of JavaScript after version 5.1, covering ES2015, ES2016, ES2017, etc., while ES2015 is the official name, specifically referring to the official version of the language released that year. standard.
Support for ES6 by major browsers: kangax
Babel
Babel is a widely used ES6 transcoder that can convert ES6 code to ES5 code to execute in the existing environment.
Babel’s configuration file is .babelrc, which is stored in the root directory of the project. The first step in using Babel is to configure this file.
Declare variables
ES5 has only two ways to declare variables: the var command and the function command. ES6 adds let, const, import and class commands. Therefore, ES6 has a total of 6 ways to declare variables.
In ES5, the properties of top-level objects are equivalent to global variables. In order to change this, ES6 stipulates on the one hand that in order to maintain compatibility, global variables declared by the var command and the function command are still attributes of the top-level object; on the other hand, it stipulates that global variables declared by the let command, const command, and class command, Properties that do not belong to the top-level object. In other words, starting from ES6, global variables will gradually be decoupled from the properties of the top-level object.
let
ES6 adds a new let command to declare variables. Its usage is similar to var, but the declared variable is only valid within the code block where the let command is located.
{ let a = 10; var b = 1; } a // ReferenceError: a is not defined. b // 1
Does not allow repeated declarations
let does not allow repeated declarations of the same variable in the same scope.
// 报错 function func() { let a = 10; var a = 1; } function func(arg) { let arg; // 报错 } function func(arg) { { let arg; // 不报错 } }
Block-level scope
ES6 allows arbitrary nesting of block-level scopes.
The inner scope can define variables of the same name in the outer scope.
The outer scope cannot read the variables of the inner scope.
{{{{ {let insane = 'Hello World' {let insane = 'Hello World'} } console.log(insane); // 报错 }}}};
Block-level scope and function declaration
ES5 stipulates that functions can only be declared in the top-level scope and function scope. Cannot be declared at block scope.
ES6 stipulates that in block-level scope, function declaration statements behave like let and cannot be referenced outside block-level scope.
Considering that the behavior caused by the environment is too different, you should avoid declaring functions in block-level scope. If it is really necessary, it should be written as a function expression instead of a function declaration statement.
There is no variable promotion
The variables declared by the let command must be used after declaration, otherwise an error will be reported.
// var 的情况 console.log(foo); // 输出undefined var foo = 2; // let 的情况 console.log(bar); // 报错ReferenceError let bar = 2;
Temporary dead zone
As long as the let command exists in the block-level scope, the variables it declares will be "binding" to this area and will no longer be affected by external influences.
var tmp = 123; if (true) { tmp = 'abc'; // ReferenceError let tmp; }
In the code block, the variable is not available until it is declared using the let command. Syntactically, this is called the "temporary dead zone" (TDZ).
const
const declares a read-only constant. Once declared, the value of a constant cannot be changed.
is only valid within the block-level scope where it is declared.
#The constants declared by the const command are not promoted. They also have a temporary dead zone and can only be used after the declared position.
const PI = 3.1415; PI // 3.1415 PI = 3; // TypeError: Assignment to constant variable.
Essence
What const actually guarantees is not that the value of the variable cannot be changed, but that the memory address pointed to by the variable cannot be changed. For simple types of data (numeric values, strings, Boolean values), the value is stored at the memory address pointed to by the variable, and is therefore equivalent to a constant. But for composite type data (mainly objects and arrays), the memory address pointed to by the variable only stores a pointer. Const can only guarantee that this pointer is fixed. As for whether the data structure it points to is variable, it is completely Can't control it anymore. Therefore, you must be very careful when declaring an object as a constant.
const foo = {}; // 为 foo 添加一个属性,可以成功 foo.prop = 123; foo.prop // 123 // 将 foo 指向另一个对象,就会报错 foo = {}; // TypeError: "foo" is read-only
If you really want to freeze the object, you should use the Object.freeze method.
const foo = Object.freeze({}); // 常规模式时,下面一行不起作用; // 严格模式时,该行会报错 foo.prop = 123;
The above is the detailed content of ES6 series declaring variables let and const. For more information, please follow other related articles on the PHP Chinese website!

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

ToimproveyourPHPwebsite'sperformance,usethesestrategies:1)ImplementopcodecachingwithOPcachetospeedupscriptinterpretation.2)Optimizedatabasequeriesbyselectingonlynecessaryfields.3)UsecachingsystemslikeRedisorMemcachedtoreducedatabaseload.4)Applyasynch

Yes,itispossibletosendmassemailswithPHP.1)UselibrarieslikePHPMailerorSwiftMailerforefficientemailsending.2)Implementdelaysbetweenemailstoavoidspamflags.3)Personalizeemailsusingdynamiccontenttoimproveengagement.4)UsequeuesystemslikeRabbitMQorRedisforb

DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

The best ways to send emails using PHP include: 1. Use PHP's mail() function to basic sending; 2. Use PHPMailer library to send more complex HTML mail; 3. Use transactional mail services such as SendGrid to improve reliability and analysis capabilities. With these methods, you can ensure that emails not only reach the inbox, but also attract recipients.

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.


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

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 English version
Recommended: Win version, supports code prompts!

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
