Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to define integer constants in JavaScript?
ECMAScript allows usage of const to define constants in JavaScript. To define integer constants in JavaScript, use the const keyword.
Syntax
const CONSTANT_NAME = value;
Example
const MY_VAL = 5;
console.log("MY_VAL:", MY_VAL);
// This will throw an error
try {
MY_VAL = 10;
} catch (error) {
console.log("Error:", error.message);
}
MY_VAL: 5 Error: Assignment to constant variable.
Key Points
As shown above, MY_VAL is a constant with value 5 assigned. Attempting to reassign another value to a constant variable throws an error.
Using const will not allow you to reassign any value to MY_VAL again. If you assign a new value to a constant, it leads to a TypeError.
Multiple Integer Constants
const MAX_SIZE = 100;
const MIN_SIZE = 1;
const DEFAULT_COUNT = 50;
console.log("MAX_SIZE:", MAX_SIZE);
console.log("MIN_SIZE:", MIN_SIZE);
console.log("DEFAULT_COUNT:", DEFAULT_COUNT);
MAX_SIZE: 100 MIN_SIZE: 1 DEFAULT_COUNT: 50
Conclusion
Use const to define integer constants in JavaScript. Once declared, constant values cannot be reassigned, making your code safer and more predictable.
Advertisements
