JavaScript(JS) Constants
In JavaScript, constants are variables that cannot be reassigned a new value once they are defined. The keyword used to declare a constant is const
. Once a value is assigned to a constant, it cannot be changed throughout the program. Here is an example:
const PI = 3.14159;So.www:ecrutheitroad.com
In this example, we declared a constant named PI
and assigned it a value of 3.14159. If we try to reassign a new value to PI
, we will get an error:
PI = 3.14; // This will throw an error
Constants are useful for declaring values that are fixed throughout the program and should not be changed. For example, you might use a constant to represent the maximum number of characters in a text input field or the number of seconds in a minute.
Note that while the value of a constant cannot be changed, it doesn't mean that the value itself is immutable. If a constant holds a reference to an object, the properties and methods of that object can still be changed. Here is an example:
const person = { name: "John", age: 30 }; person.age = 31; // This is allowed console.log(person); // Output: { name: "John", age: 31 }
In this example, we declared a constant named person
and assigned it an object with two properties (name
and age
). While we cannot reassign a new value to person
, we can still modify the properties of the object it references.