0

I want to do sth like this (c++):

const int SIZE = 5;
int array[SIZE];

but in JS. I'm using the SIZE value many times (for many arrays and later in the code) and I don't want to put many literals with the same value (in case I have to edit it later). I read somewhere that there's a const keyword in JS but it doesn't work in every browser (not sure if that's true but I want a universal solution). And the shorter/simpler the better! ;)

NPS
  • 6,003
  • 11
  • 53
  • 90

3 Answers3

1

You could just assign a

var arr = new Array(5);

which initializes an array with a length property of 5 but no values (sparse array).

Declaring variable types as in C++ is not possible, as JS is a loose typed language, also there are no arrays with a fixed length - Arrays are more like lists. For the const keyword, have a look at this question.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

The const keyword is in fact non-standard, and only implemented by Mozilla therefore not guaranteed to work cross-browser (but apparently some browsers implement it, see the link on Bergi's answer). Just use a regular variable, and the uppercase name to indicate it's supposed to be a constant:

var SIZE = 5;
var arr = new Array(SIZE);

Note: if you pass anything other than a number to the Array constructor, it will create an array with length and the value you passed at index 0. In that case, it's best to just use the literal notation (var arr = ['foo']). Also keep in mind that when you pass a number to the constructor, you're just setting the initial length, and it's always possible to add or remove elements after that.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • Of course... I guess all arrays in JS are dynamic? Meaning that I can always use a variable (instead of const) and the array will create without a problem? :P – NPS Dec 14 '12 at 11:41
  • Exactly. And actually, the value you pass to the constructor is just the initial length, you can always add/remove elements after that. – bfavaretto Dec 14 '12 at 11:43
1
Object.defineProperty(window, PI, {
    configurable: false,
    writeable: false,
    value: 3.1415
});

console.log(PI); // 3.1415

/* if 'use strict', the acts below would throw error */

PI = 0; // nothing happened

window.PI = 0; // nothing happened

delete window.PI;  // nothing happened

Object.defineProperty(window, PI, {
    configurable: true,
    writeable: true,
    value: 0
}); // nothing happened

console.log(PI); // 3.1415

array or object can also define its attributes as 'const' with

Object.defineProperties

but the fastest way is

Object.freeze(obj_name)

but you have to ensure that the object itself is a 'const' then its attributes are in real safe

kenberkeley
  • 8,449
  • 3
  • 35
  • 25