Constant Array in JavaScript

Viewed 437

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 !
3 Answers

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;

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]
Related