Another Javascript trap with arrays

JavaScript arrays are a famous source of trouble. E.g. when you access index out of bounds, you don’t get an exception, you get undefined. This, by the way, breaks type checking at TypeScript, but I digress. It turns that in V8, the most popular JavaScript engine, maximum possible array index is 4294967295, or 232-1.

What happens if you use a bigger index? No problem, it would be converted to a named property, but the length of the array would remain unchanged. Basically arr[5_000_000_000]=42 is equivalent to arr.random_name = 42.

Consider this code:

function len(idx) {
  const x = [];
  x[idx] = 42;
  return x.length;
}

console.log(len(1)); // 2
console.log(len(100)); // 101
console.log(len(4_000_000_000)); // 4000000001
console.log(len(5_000_000_000)); // 0

Isn’t JavaScript fun?

TypeScript version behaves the same, adding type annotations does not change much.

Leave a Reply

Your email address will not be published. Required fields are marked *