JavaScript Constants (Live Playground)
In JavaScript, constants are variables that cannot be reassigned once they have been initialized. Constants are useful when you need to store a value that should not be changed during the execution of your program. In this tutorial, we'll explore the use of constants in JavaScript and learn how to declare and work with them using the const
keyword.
Declaring Constants
To declare a constant in JavaScript, use the const
keyword followed by the constant name and its value. The name of a constant should be in uppercase letters with words separated by underscores to indicate that the value should not be changed.
Example:
const PI = 3.14159;
console.log(PI); // Output: 3.14159
In the example above, we declare a constant named PI
and assign it the value 3.14159
.
Constants and Immutability
Although constants cannot be reassigned, they are not necessarily immutable. For example, if a constant is an object or an array, its properties or elements can still be modified.
Example:
const COLORS = ['red', 'green', 'blue'];
console.log(JSON.stringify(COLORS)); // Output: ["red","green","blue"]
COLORS.push('yellow');
console.log(JSON.stringify(COLORS)); // Output: ["red","green","blue","yellow"]
In the example above, the COLORS
constant is an array. Although the array itself cannot be reassigned, its elements can be modified, such as adding a new color to the array.
Constants and Scope
Constants follow the same scoping rules as variables declared with the let
keyword. They have block scope, meaning they are accessible only within the block in which they are declared.
Example:
if (true) {
const MESSAGE = 'Hello, world!';
console.log(MESSAGE); // Output: Hello, world!
}
console.log(MESSAGE); // Error: MESSAGE is not defined
In the example above, the MESSAGE
constant has a block scope and cannot be accessed outside the if
statement block.
Conclusion
Constants in JavaScript are useful for storing values that should not be changed during the execution of your program. Use the const
keyword to declare constants, and remember that constants have block scope, like variables declared with the let
keyword. While constants cannot be reassigned, their properties or elements can still be modified if they are objects or arrays.