Home > Web Front-end > JS Tutorial > body text

What is the meaning of const in javascript

WBOY
Release: 2022-03-31 10:55:07
Original
8046 people have browsed it

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;".

What is the meaning of const in javascript

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

What is the meaning of const in javascript

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>
Copy after login

Output result:

What is the meaning of const in javascript

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

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template