Question from the Typescript - Overview test

How to declare an immutable (non-modifiable) variable in TypeScript?

Easy

How do you declare an immutable (non-modifiable) variable in TypeScript?

Author: Vincent CotroStatus: PublishedQuestion passed 436 times
Edit
0
Community Evaluations
developer avatar
Incorrect answer
Jake
08/11/2023
Values that are declared with const CAN be modified but they cannot be reinitialized or set to another variable. The moderators marked this as wrong, but it is CORRECT........ and it is easy to test! Here is an example, tryin your code editor: const arr = [1,2,3] arr.push(4) console.log(arr) // You will see that the array indeed receives a new value. // However, you cannot reinitialized the array. For example, const newArr = [1]; newArr = [2] // This will throw an error. "Assignment to constant variable"
developer avatar
Vincent Cotro
07/11/2023
Can you give me an exemple ?
developer avatar
Jake
08/11/2023
My response is correct. Was this site built by non developers? In typescript, try: const arr = [1,2,3] arr.push(4) console.log(arr) You will see that the array indeed receives a new value. However, you cannot reinitialized the array. For example, const arr = [1]; arr = [2] // This will throw an error. "Assignment to constant variable"
developer avatar
Auteur anonyme
22/02/2024
I agree with @Jake. const does not ensure that a variable is immutable but readonly does.