Constants
Constants
Use the const keyword to create a read-only, named constant. Constant identifiers follow the same naming rules as variables: start with a letter, underscore, or dollar sign ($), and contain alphabetic, numeric, or underscore characters.
const PI = 3.14;
Constants cannot be reassigned or redeclared. They must be initialised and follow the same scope rules as let block-scope variables.
You cannot declare a constant with the same name as a function or variable in the same scope. For example:
// THIS WILL CAUSE AN ERROR
function f() {}
const f = 5;
// THIS WILL CAUSE AN ERROR TOO
function f() {
const g = 5;
var g;
}
However, const only prevents re-assignments, not mutations. Object properties assigned to constants aren't protected, so the following statement executes without problems.
const MY_OBJECT = { key: "value" };
MY_OBJECT.key = "otherValue";
Also, the contents of an array are not protected, so the following statement is executed without problems.
const MY_ARRAY = ["HTML", "CSS"];
MY_ARRAY.push("JAVASCRIPT");
console.log(MY_ARRAY); // ['HTML', 'CSS', 'JAVASCRIPT'];