How can I keep an array of constants in JavaScript?
And likewise, when paring, 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 !
How can I keep an array of constants in JavaScript?
And likewise, when paring, 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 !
Share
Improve this question
asked Jan 10, 2021 at 21:30
Alexandra Danith AnsleyAlexandra Danith Ansley
3382 silver badges15 bronze badges
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. – Alexandra Danith Ansley Commented Jan 11, 2021 at 17:03
3 Answers
Reset to default 8With 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 mon 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 pile-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;
I have not investigated thoroughly, but it is inferred that JS will have immutable native types, here is a presentation:
https://2ality./2020/05/records-tuples-first-look.html
const vector = #[1, 2, 3, 4]; // immutable
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]