JS Basic Tutorial
The const keyword in JavaScript is used to define variables that cannot be changed once they’re assigned a value. This prevents any modifications to the variable’s value.
const
:1) Block Scope:
Similar to let, const is block-scoped. This means that the variable declared with const is only accessible within the block in which it is defined.
Try it yourself
2) No Reassignment:
A variable declared with const cannot be reassigned after it is initialized. Once a value is assigned, it remains constant.
Try it yourself
3) Must Be Initialized:
Unlike let or var, a const variable must be initialized at the time of declaration. You cannot declare a const variable without assigning it a value.
Try it yourself
4) Hoisting:
Like let, const variables are hoisted to the top of their block, but they remain in the Temporal Dead Zone (TDZ) until they are initialized. This means you cannot access the variable before the point in the code where it is declared.
Try it yourself
5) Constant Reference, Not Immutable Data:
With objects and arrays, const makes the reference to the variable immutable, but the contents of the object or array can still be modified.
Try it yourself
6) No Re-declaration:
Similar to let, you cannot re-declare a const variable in the same scope.
Try it yourself