2. JavaScript Variables
2.4. Using const
Much like variables defined using the let statement, constants are block-scoped. The const
declaration creates a constant whose scope is often either global or local to the declared block during
which we declare it. The value of a constant is read-only; you cannot change it through reassignment,
and you cannot redeclare it. An initializer for a constant is required; i.e., you want to specify its value
within the same statement in which it is declared (since you cannot alter it later). A function or a
variable within the same scope cannot have the same name as the variable.
Declaring your constants in uppercase is a good practice, because this may help programmers
differentiate the constants from other variables within the program.
Refer to the given example:
- <html>
- <body>
- <h2>Use const to declare a variable</h2>
- <script>
- var x = 5;
- const GREETING = "Hi, Pisay </br>";
- document.write(GREETING);
- document.write("The value of variable x is: " + x);
- </script>
- </body>
- </html>