I keep thinking that it is a constant variable
This is actually an oxymoron. "Variable" means "not constant" and "constant" means "not variable". I suspect that you are thinking about immutability.
In JavaScript, var strAnimal = 'Fox';
could be interpreted like so:
- You declare a variable called
strAnimal
- You initialize this variable by assigning a string to it
Strings (like all primitive values) are immutable in this language, meaning that you cannot alter the integrity of 'Fox'
.
var str = 'bar';
str.split(); // ["bar"]
str.toUpperCase(); // BAR
str.replace('r', 'z'); // baz
console.log(str); // The original string has not changed...
On the contrary, objects are mutable. See what happens with arrays:
var arr = ['foo', 'bar', 'baz'];
arr.pop();
arr.shift();
arr.unshift('quux');
arr.push('corge');
console.log(arr); // The original array has changed...
Do not think constants are immutable because, even in ES6, constants are not immutable. They just prevent reassigning. Look at this example:
const obj = {};
obj.foo = 'Foo';
obj.bar = 'Bar';
console.log(obj); // The original object has changed...
obj = 'Baz'; // TypeError
To have an immutable constant in this case, you should use Object.freeze()
:
const obj = {};
Object.freeze(obj);
obj.foo = 'Foo';
obj.bar = 'Bar';
console.log(obj); // The original object has not changed...