In JavaScript, const means "unchanged" and is a keyword used to declare one or more constants. They must be initialized when declaring, and the value cannot be modified after initialization. If it is changed The value of a constant will cause a type error, and the syntax is "const constant name = constant value;".
The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.
ES2015 (ES6) has added two important JavaScript keywords: let and const.
The variables declared by let are only valid within the code block where the let command is located.
const declares a read-only constant. Once declared, the value of the constant cannot be changed.
Used to declare one or more constants, which must be initialized when declaring, and the value cannot be modified after initialization
Const defined constants are similar to variables defined using let:
Both are block-level scopes
Neither can have the same name as other variables or functions in its scope
There are two differences between the two:
Constant declared by const must be initialized, while variables declared by let The value of a constant defined without
const cannot be modified through reassignment, nor can it be declared again. The values of variables defined by let can be modified.
The example is as follows:
<html> <head> <meta charset="utf-8"> <title>123</title> </head> <body> <h2>JavaScript const</h2> <p>const 用于声明一个或多个常量,声明时必须进行初始化,且初始化后值不可再修改。</p> <p id="demo"></p> <script> try { const PI = 3.141592653589793; PI = 3.14; } catch (err) { document.getElementById("demo").innerHTML = err; } </script> </body> </html>
Output result:
[Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of What is the meaning of const in javascript. For more information, please follow other related articles on the PHP Chinese website!