4

Possible Duplicate:
Are Javascript arrays sparse?

Is the following "safe" in JavaScript? (as in, can be expected to work reliably on all JavaScript engines)

a = [];
a[100] = "hello";

a[100] == "hello"; // should be true
Community
  • 1
  • 1
  • http://stackoverflow.com/questions/1510778/are-javascript-arrays-sparse – Brad Jul 06 '12 at 04:44
  • Yes, it will work everywhere. But if you don't actually need array-specific functionality, like `.length`, use an object instead: `var a = {};` – Ry- Jul 06 '12 at 04:51

3 Answers3

6

Yes. Arrays in JavaScript are sparse and your code is expected to work in all JavaScript implementations.

You can get into requirements in the section 15.4 of the specification(PDF).

Short summary: array is special object that have length property adjusted when one adds elements at properties with numeric names (like `a[123]="test"). Other methods like join take length into account duuring operations.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0

Yes, why wouldn't it work? Its perfectly acceptable syntax.

Jakub
  • 20,418
  • 8
  • 65
  • 92
  • Syntactically yes, but I was just wondering if initializing items at arbitrary indices was well-defined behavior in JavaScript. –  Jul 06 '12 at 04:44
  • 1
    @rfw, it is well defined in that it is valid in the language, but how the implementation is done may vary. See also http://stackoverflow.com/a/1510842/362536 – Brad Jul 06 '12 at 04:46
  • There are lots of statements that are "acceptable syntax" that will just not work. – Ted Hopp Jul 06 '12 at 04:46
0

You can even assume

a[100] === "hello"; // will return true
andyzinsser
  • 2,463
  • 2
  • 18
  • 18