0

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.

2
  • As mentioned here, 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? Commented Dec 9, 2022 at 7:02
  • yes, I want to avoid mutations. Commented Dec 9, 2022 at 7:03

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.