-1

What is the javascript equivalent for typescript's const assertion?

const arr = [1,2,3,4] as const

I want to achieve this array in javascript to avoid further mutation.

Kaneki21
  • 1,323
  • 2
  • 4
  • 22
  • As mentioned [here](https://stackoverflow.com/a/66993654), at runtime, there is no difference with using `as const`. So, what is the expected behavior in javascript and why do you need this? Do you want avoid mutations on `arr`? – adiga Dec 09 '22 at 07:02
  • yes, I want to avoid mutations. – Kaneki21 Dec 09 '22 at 07:03

1 Answers1

5

Yes, Use Object.freeze

const arr = [1, 2, 3, 4, 5];
Object.freeze(arr);

arr.push(8); // Uncaught TypeError: Cannot add property 5, object is not extensible
adiga
  • 34,372
  • 9
  • 61
  • 83
Anil kumar
  • 1,216
  • 4
  • 12