2

How can I keep an array of constants in JavaScript?

And likewise, when comparing, it gives me the correct result.

Example,

const vector = [1, 2, 3, 4];

vector[2] = 7; // An element is not constant!

console.log(JSON.stringify(vector));
// [1,2,7,4] ... Was edited

// OR
const mirror = [1, 2, 7, 4];

console.log(`are equals? ${vector == mirror}`);
// false !
1
  • Thanks for the answers. I tried clicking "This answare is useful", but stackoverflow won't let me do it yet. I'm new around here. Commented Jan 11, 2021 at 17:03

3 Answers 3

7

With Object.freeze you can prevent values from being added or changed on the object:

'use strict';
const vector = Object.freeze([1, 2, 3, 4]);

vector[2] = 7; // An element is not constant!

'use strict';
const vector = Object.freeze([1, 2, 3, 4]);
vector.push(5);

That said, this sort of code in professional JS is unusual and a bit overly defensive IMO. A common naming convention for absolute constants is to use ALL_CAPS, eg:

const VECTOR =

Another option for larger projects (that I prefer) is to use TypeScript to enforce these sorts of rules at compile-time without introducing extra runtime code. There, you can do:

const VECTOR: ReadonlyArray<Number> = [1, 2, 3, 4];

or

const VECTOR = [1, 2, 3, 4] as const;
Sign up to request clarification or add additional context in comments.

Comments

1

I have not investigated thoroughly, but it is inferred that JS will have immutable native types, here is a presentation:

https://2ality.com/2020/05/records-tuples-first-look.html

const vector = #[1, 2, 3, 4]; // immutable

Comments

1

The const keyword can be confusing, since it allows for mutability. What you would need is immutability. You can do this with a library like Immutable or Mori, or with Object.freeze:

const array = [1,2,3]
Object.freeze(array)
array[0] = 4
array // [1,2,3]

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.