JavaScript const
JavaScript const keyword is used to declare a constant value. A constant has to be declared and immediately initialized. Meaning, declaration and initialization of a constant has to happen in a single statement.
A constant once initialised, cannot be modified.
The syntax to define a constant pi
with value 3.14
is
</>
Copy
const pi = 3.14;
Example
In the following example, we create a constant pi with value 3.14 and use it as inner HTML for a pre HTML element.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
const pi = 3.14;
document.getElementById('output').innerHTML += pi;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned what constants are, how to declare/initialize them, and how to use them in a program, with examples.