Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I can change const array in TypeScript

Can you explain why I can change const array in TypeScript, but other types I cant change?

Example:

let readOnlyArray: readonly string[] = ["Apple", "Orange", "Banana"];
console.log(readOnlyArray);
readOnlyArray[0] = "TOMATO"; // !ERROR because array has read only type

const constArray: string[] = ["Apple", "Orange", "Banana"];
console.log(constArray); // Output: [ 'Apple', 'Orange', 'Banana' ]
constArray[0] = "TOMATO";
console.log(constArray); // Output: [ 'TOMATO', 'Orange', 'Banana' ] 

But, when I try to change other type of const I get error, because I cant change const.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const apple: string = "apple";
apple = "TOMATO"; // !ERROR - you cant change const

const myNum: number = 1;
myNum = 2; // !ERROR - you cant change const

// etc...

>Solution :

This is a good question! If you’re curious for a more in-depth answer, check out the reply here: Why can I change a constant object in javascript.

Otherwise I can give you a really short summary.

Setting a variable as a constant only guarantees two things:

  • The constant cannot change through re-assignment
  • The constant cannot be re-declared

Since in this case you are doing neither of those things, no error will be generated!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading