Home »
JavaScript
const in JavaScript
JavaScript const: Here, we are going to learn about the const in JavaScript, how to create a constant in JavaScript?
Submitted by IncludeHelp, on February 01, 2019
const
Like other programming languages, JavaScript also provide the feature to create constants, we can make any identifier as constant by using the "const".
"const" is a keyword in JavaScript and it makes an identifier constant.
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.
JavaScript Tutorial »