0

In javascript, if I create a const array, I can still modify the object the variable points to:

// The const declaration creates a read-only reference to a value. 
// It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
const x = [1,2,3];
x.push(4);
console.log(x);
x=55 // But this is illegal and will error
console.log(x);

Is there a way to make the elements in an array immutable as well? Similar to something like const int* const x; in C?

1
  • Object.freeze(x) will work Commented Feb 4, 2022 at 1:02

2 Answers 2

4

You can use Object.freeze to prevent an object (or array) from being changed:

const x = [1, 2, 3];
Object.freeze(x);

x.push(4); // This will throw an exception
Sign up to request clarification or add additional context in comments.

Comments

1

objects frozen with Object.freeze() are made immutable.

Here are the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

Example:

const x = [1,2,3];
Object.freeze(x);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.