JavaScript Statement: const
[this page | pdf | back links]
In JavaScript,
the const statement declares
a constant. This is akin to a variable defined using a var statement, see here, or a let statement, see here, but with
the variable being unable to be changed thereafter. Both the const and the var statements were introduced by ECMAScript 2015.
It is generally
considered good practice to define variables as constants if they are not going
to change, as it reduces the risk of them being accidentally overwritten.
EXAMPLE:
HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x or error</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>
<script>
document.getElementById("Example").innerHTML =
'var x;'
+ '<br>const y = 0;'
+ '<br>try { y = 1; x = y } catch (err) { x = err; }'
var x;
const y = 0;
try { y = 1; x = y } catch (err) { x = err; }
document.getElementById("Result").innerHTML = x
</script>
</body>
</html>
|
NAVIGATION LINKS
Contents | Prev | Next | JavaScript Reserved Words