0

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.

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

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

// etc...
Oles Yudin
  • 13
  • 4

2 Answers2

-1

When you're adding to an array or object, you're not re-assigning or re-declaring the constant, it's already declared and assigned, you're just adding to the "list" that the constant points to.

Unlike a variable, which it's purpose is the value assigned to it.

therefor, you can add a value to an array or object (even a const), but can not do it for a variable)

const arr = []

arr.push(2) //This is Ok

const myVar = "this is constant"

myVar = "constant" //Error !
Shachar297
  • 599
  • 2
  • 7
-1

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!

IndevSmiles
  • 737
  • 6
  • 17