const (const)
Like other programming languages, JavaScript also provide the feature to create constants, we can make any identifier as constant by using the "const".
与其他编程语言一样,JavaScript也提供了创建常量的功能,我们可以使用“ const”将任何标识符设为常量。
"const" is a keyword in JavaScript and it makes an identifier constant.
“ const”是JavaScript中的关键字,它使标识符恒定。
Syntax:
句法:
const identifier_name = value;
Points to remember:
要记住的要点:
While creating a constant, a value should be assigned.
创建常数时,应分配一个值。
A constant’s value cannot be changed.
常量的值不能更改。
Error
错误
If we try to change the value of a constant following type error throws:
如果我们尝试更改以下常量的值,则会引发类型错误:
TypeError: Assignment to constant variable.
Example:
例:
<html>
<head>
<title>JavaScipt Example</title>
</head>
<body>
<script>
const url = "www.example.com";
const port_no = 25;
//printing...
document.write("url: " + url + "<br>");
document.write("port_no: " + port_no + "<br>");
//if you will try to change the value
//it will not be changed
try{
port_no = 21;
}
catch(err){
document.write(err + "<br>");
}
</script>
</body>
</html>
Output
输出量
url: www.example.com
port_no: 25
TypeError: Assignment to constant variable.
翻译自: https://www.includehelp.com/code-snippets/const-in-javascript.aspx