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