-1

I am struggling to think about the correct terminology on a fundamental programming concept.

What do we call the variable/concept of having multiple references to a variable to easily maintain the values or make sure the values are consistent?

Example:

var strAnimal = 'Fox';

console.log('the quick brown' + strAnimal + 'jumps over the lazy dog')
console.log('A man screaming is not a dancing.' + strAnimal + 'Life is not a spectacle.')
console.log('And maybe... you are a little' + strAnimal + 'with no wings, and no feathers')

I keep thinking that it is a constant variable, but I don't think it is correctly called that.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

2 Answers2

1

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:

  1. You declare a variable called strAnimal
  2. 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...
Badacadabra
  • 8,043
  • 7
  • 28
  • 49
0

You can change the value of a variable, by setting a different value to it directly or let a function operate on it. But you can't change the value of a constant.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dishonered
  • 8,449
  • 9
  • 37
  • 50