Home >Web Front-end >JS Tutorial >Are there constants in JavaScript?
In JavaScript, there are multiple ways to define constants.
Since ES2015, JavaScript has added the const keyword to declare constants:
const MY_CONSTANT = "some-value";
const constants are immutable, meaning their value cannot be changed once assigned.
Prior to ES2015, JavaScript did not have a dedicated keyword for constants. As a common practice, developers used variables declared with var in all caps to indicate that they should not be modified:
var MY_CONSTANT = "some-value";
However, these variables are still mutable, so this approach relies on conventions rather than strict enforcement.
const is widely supported in modern browsers and Node.js. It works in all browsers except IE 8, 9, and 10. Some browsers may also require strict mode to be enabled for const to function correctly.
For legacy code or environments where const is not supported, the var convention can still be used to indicate that variables should be treated as constants.
The above is the detailed content of Are there constants in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!