Constants
A constant is a modifier keyword that marks a value as immutable. Use a constant when a value should always stay the same. Some examples of good usages:
- Mathmetical values like
PI - Fixed settings
- Values that should never be reassigned
- Named or IDs that stay the same
A constant is a modifier keyword that makes a variable immutable. A constant is declared with the
constmodifier.
Variables
A variable can be marked as a constant by using the const modifier.
const timeLimit = 100; // timeLimit is now a constant, its value can never change
timeLimit = 50; // Throws an error: 'cannot assign value to timeLimit'
A constant can also be combined with a local variable.
function handleTimer() {
local const timeLimit = 100;
}
Classes
A property of a class can also be assigned with a const modifier.
class Math {
const PI = 3.1415926535
}
local math = new Math()
math.PI = 3 // Not allowed, as PI is a constant
This also works for static classes
static class Math {
static const PI = 3.1415926535
}
Math.PI = 3 // Not allowed, as PI is a constant