I want to do sth like this (c++):
const int SIZE = 5;
int array[SIZE];
but in JS. I’m using the SIZE value many times (for many arrays and later in the code) and I don’t want to put many literals with the same value (in case I have to edit it later). I read somewhere that there’s a const keyword in JS but it doesn’t work in every browser (not sure if that’s true but I want a universal solution). And the shorter/simpler the better! 😉
The
constkeyword is in fact non-standard,and only implemented by Mozillatherefore not guaranteed to work cross-browser (but apparently some browsers implement it, see the link on Bergi’s answer). Just use a regular variable, and the uppercase name to indicate it’s supposed to be a constant:Note: if you pass anything other than a number to the
Arrayconstructor, it will create an array withlengthand the value you passed at index0. In that case, it’s best to just use the literal notation (var arr = ['foo']). Also keep in mind that when you pass a number to the constructor, you’re just setting the initiallength, and it’s always possible to add or remove elements after that.