A Caveat When Declaring Javascript Arrays

A friend at work was having a bizarre Javascript array problem yesterday. The solution seems perfectly obvious now but took a minute to figure out.

He was writing a small page the involved doing a bunch of calculations based on some options. Various numeric values to be used in those calculations were stored in a set of arrays, sort of like this:

~~~~ {.javascript name="code"} var foo = new Array(4001, 1234, 5678);var bar = new Array(5921); wzxhzdk:0

bar kept showing up like this:

~~~~ {.javascript name="code"} [undefined, undefined, undefined, undefined, 5917 more...] wzxhzdk:1

See that last one? Our code for bar up above doesn't realize we want to put the value 5921 into element 0 of the array. It thinks we wanted to create an empty array with 5921 elements!

Changing the code to this fixed the problem:

~~~~ {.javascript name="code"} var bar = new Array(5921,0); ~~~~