Javascript: Why does a const variable behave differently for arrays and objects?

What do you think the output of the code below will be 🤔 ?

const myName: string = 'John';
myName = 'Eric';

You guessed it right 👍 We can’t change the value of a constant variable after it has been declared and assigned. Here’s the error-message:

error: TS2588 [ERROR]: Cannot assign to 'myName' because it is a constant.
myName = 'Eric';
~~~~~~
at file:///home/runner/WeepyWarlikeVirus/index.ts:2:1
exit status 1

The same rule applies to boolean & number data-types.

const myAge: number = 34;
const isFemale: boolean = true;
myAge = 23;
isFemale = false;

But what happens when you to try to change the contents of a constant object 🤔 ?

interface Employee {
name: string,
age: number,
isFemale: boolean
}
const john: Employee = {
name: 'John',
age: 30,
isFemale: false
};
john.age = john.age + 1;
console.log(john);

If you guessed that the above code executes successfully, then you’re right 😃 ! But why? Should a variable declared to be a constant be allowed to change 🤔 ?

This has got to do with how the variables are stored inside the memory. The values of boolean, string & number variables are stored in the memory location assigned to those variables. However, when an object variable is created, then the contents of that object are created in another part of the memory. The memory address, where the object contents are stored, is stored in the memory location assigned to the john variable, as a pointer.

So, when we’re changing the values of the john object, we’re not really changing the contents of the memory location assigned to the john variable, but the contents of the john object 💡. However, if you try to assign a new object to the john variable, then you will not able to do it! For example, the following code would throw an error!

const newPerson: Employee = {
name: 'Eric Cartman',
age: 20,
isFemale: false
};
john = newPerson

The above code will throw an error:

error: TS2588 [ERROR]: Cannot assign to 'john' because it is a constant.
john = newPerson
~~~~
at file:///home/runner/WeepyWarlikeVirus/index.ts:35:1
exit status 1

The same applies to arrays!

const primeNumbers: Array<number> = [1, 2, 3, 5, 7];
primeNumbers.push(11);

If you want to make objects and arrays immutable, use Object.freeze().

Object.freeze(john);
Object.freeze(primeNumbers)

I hope you now have a better understanding of how constant variables behave in Typescript. Let me know if you have question 👍 .

Nom Nom

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store