JavaScript Const - How to use 'const' keyword in JavaScript
JavaScript Assignment Operators
- The const keyword was introduced in ES6 (2015).
- Variables defined with const cannot be Redeclared.
- Variables defined with const cannot be Reassigned.
- Variables defined with const have Block Scope.
Cannot be Reassigned
- A const variable cannot be reassigned.
Sample Code
Output
Correct
- const PI = 3.14159265359;
Incorrect
- const PI;
- PI = 3.14159265359;
When to use JavaScript const ?
Always declare a variable with const when you know that the value should not be changed.
- Use const when you declare.
- A new Array
- A new Object
- A new Function
- A new RegExp
Constant Arrays
- You can change the elements of a constant array: