How to Declare Constant in JavaScript: Syntax and Examples
In JavaScript, you declare a constant using the
const keyword followed by the constant name and its value. Constants cannot be reassigned after declaration, ensuring their value stays the same throughout the program.Syntax
To declare a constant in JavaScript, use the const keyword, then the name of the constant, an equals sign, and the value you want to assign. The value must be assigned immediately and cannot be changed later.
- const: keyword to declare a constant
- name: the identifier for the constant
- =: assignment operator
- value: the fixed value assigned to the constant
javascript
const PI = 3.14;
Example
This example shows how to declare a constant and use it in a calculation. Trying to change the constant value will cause an error.
javascript
const MAX_USERS = 100; console.log('Maximum users allowed:', MAX_USERS); // Uncommenting the next line will cause an error // MAX_USERS = 200;
Output
Maximum users allowed: 100
Common Pitfalls
One common mistake is trying to reassign a constant after it is declared, which causes an error. Another is declaring a constant without initializing it, which is not allowed.
javascript
/* Wrong: Reassigning a constant */ const SPEED_LIMIT = 60; // SPEED_LIMIT = 80; // Error: Assignment to constant variable. /* Wrong: Declaring without initialization */ // const TAX_RATE; // Error: Missing initializer in const declaration /* Right: Declare and assign immediately */ const TAX_RATE = 0.07;
Quick Reference
| Concept | Description |
|---|---|
| const | Keyword to declare a constant |
| Initialization | Must assign a value when declaring |
| Reassignment | Not allowed after declaration |
| Scope | Block-scoped, like let |
| Use case | Values that should not change |
Key Takeaways
Use
const to declare constants that cannot be reassigned.Always assign a value when declaring a constant with
const.Constants are block-scoped, similar to variables declared with
let.Trying to change a constant's value causes a runtime error.
Use constants to protect values that should remain fixed throughout your code.