Can I Change a Constant Variable in JavaScript?
Asked by
cobalt test!
I'm a beginner learning JavaScript, and I've come across a concept that confuses me. The book says that once a constant is created, it cannot be changed. For example, I define a constant by writing: const EarthDiameter = 4836; If later I want to update that value to 4900 based on new information, am I out of luck? Can I just delete the constant and create a new one, or what should I do?
Answers
Haha, yeah, you can't change a constant once it's set in the same program. If you try to reassign it later, you'll run into an error. So, if you need a variable that might change, you'd want to use 'let' instead!
Reply to this answer
Right! Using 'const' means you're telling both the compiler and yourself that this value should remain constant within its scope. If you need to update it later, then just define a new 'const' instead of trying to modify the old one.
Reply to this answer
The best approach here is to test it out! Try declaring a const and then modify it in the console, you'll see what happens. Or, within a script, if you incorrectly try to change it, you'll get an error. Just remember, when using 'const', the variable itself can't be reassigned, but if it's an object or array, you can change its contents!
Reply to this answer
Exactly! It's not that the value is written in stone, but rather that the binding of the variable to that value cannot change. If you want to change a value often, stick with 'let' instead of 'const'.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions