Constants in JavaScript
A constant in programming is essentially a variable whose value can’t be changed. It’s destined to be what you tell it it is forever. This is useful when you want to set a really important value at the start of your program that you don’t want to accidentally change, or have your program amend it without you noticing. Luckily, in these modern times we can use constants in JavaScript by using the const
keyword like so:
const MY_NAME = 'Bobbin';
It’s encouraged to declare your constant by putting its name in all uppercase letters to distinguish it from variables. Now, let’s try to change it…
const MYNAME = "Bobbin'; MYNAME = 'Guybrush'; // Doesn't throw an error console.log(MY_NAME); // Prints 'Bobbin' to the console
So, you’ll see that we’re allowed to assign things to constants, but they won’t have any effect. Well, that is if you’re using Chrome or Firefox. Sadly, if you’re using Safari or Opera then this will happen:
const MYNAME = 'Bobbin'; MYNAME = 'Guybrush'; console.log(MY_NAME); // Prints 'Guybrush' to the console. WAT.
Crazy. It just gets treated like a normal variable, making you throw your hands up, look at the sky and ask “what’s the point of anything?” Also, you might be wondering if the const
keyword works on IE? Of course not.