Const in JavaScript
Variables declared with the const maintain constant values. const declarations share some similarities with let declarations.
Like let declarations, const declarations can only be accessed within the block they were declared.
This means that the value of a variable declared with const remains the same within its scope. It cannot be updated or re-declared. So if we declare a variable with const, we can neither do this:
const greeting = "say Hi";
greeting = "say Hello instead";// error: Assignment to constant variable.
nor this:
const greeting = "say Hi";
const greeting = "say Hello instead";// error: Identifier 'greeting' has already been declared
Every const declaration, therefore, must be initialized at the time of declaration.
This behavior is somehow different when it comes to objects declared with const. While a const object cannot be updated, the properties of this objects can be updated. Therefore, if we declare a const object as this:
const greeting = {
message: "say Hi",
times: 4
}
while we cannot do this:
greeting = {
words: "Hello",
number: "five"
} // error: Assignment to constant variable.
we can do this:
greeting.message = "say Hello instead";
This will update the value of greeting.message without returning errors.
Just like let, const declarations are hoisted to the top but are not initialized.
So just in case you missed the differences, here they are:
vardeclarations are globally scoped or function scoped whileletandconstare block-scoped.varvariables can be updated and re-declared within its scope;letvariables can be updated but not re-declared;constvariables can neither be updated nor re-declared.- They are all hoisted to the top of their scope. But while
varvariables are initialized withundefined,letandconstvariables are not initialized. - While
varandletcan be declared without being initialized,constmust be initialized during declaration.
The const keyword was introduced in ES6 (2015).
- Variables defined with
constcannot be Redeclared. - Variables defined with
constcannot be Reassigned. - Variables defined with
consthave Block Scope.
When to use JavaScript const? As a general rule, always declare a variable with const unless you know that the value will change.
The const keyword was introduced in ES6 (2015).
Scope
- Block scoped always
- Start to end of the current scope anywhere
Redeclaration
- No, can't redeclare or reinitialize it
Hoisting
- Hosted at top of some private and only available after assigning value
- Can not be used before the declaration
Comments