Advertisement

Google Ad Slot: content-top

Javascript const

~1 min read · JS
On this page

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.


Key Features of 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.


Example

Javascript Const Block Scope

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.


Example

Javascript Const Reassignment

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.


Example

Javascript Const Initialization

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.


Example

Javascript Const Hoisting

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.


Example

Javascript Const Reference

Try it yourself

6) No Re-declaration:

 

    Similar to let, you cannot re-declare a const variable in the same scope.

Example

Javascript Const Redeclaration

Try it yourself