The const
statement is used to declare a variable of block scope, which is constant and must be initialized with a value at the beginning.
const variableName = "must assign a value on declaration";
The const
keyword is associated with a name. The name is attached to the right side of the const
keyword, the name becomes a variable name.
const hello = "Ola"
if(true) {
const hello = "Hello"; // a different variable
console.log(hello); // prints: Hello
}
console.log(hello); // prints: Ola
hello = "Hi"; // Throws error
console.log(hello);
const name; // Throws error. Solution: Needs to be assigned a value at the start
The const
declarations are used to declare a constant whose value does not change throughout the block to which it is assigned. Duplicate assignments and declarations will trigger an error. The const
statement requires the variable to be initialized at the time of creation.