Press enter to see results or esc to cancel.

JavaScript: iteration trickery

If you’ve ever written a line or two of HTML, JavaScript and/or CSS, I’m sure it has happened to you too. You program your application in one browser believing that in 2013 it should work anywhere anyway. Then you open your application in another browser and you see a blank screen and strange errors in the debugging console. Even though we can always read about the importance of standardisation and following them, there still stay some edge cases where your code behaves differently in different browsers.

One of those cases is iteration over typed arrays with a for … in statement. This is the test code:

var arr = new Float32Array([0, 1, 2, 3]);
for(var i in arr) {
  console.log("arr[" + i + "]", arr[i]);
}

for(var j = 0; j<arr.length; j++) {
  console.log("arr[" + j + "]", arr[j]);
}

 

This code looks totally innocent to someone with PHP background, right? Obviously the result should be

arr[0] 0
arr[1] 1
arr[2] 2
arr[3] 3
arr[0] 0
arr[1] 1
arr[2] 2
arr[3] 3

 

In Firefox it works as excepted. However, Chrome and Opera disagree. Their output looks something like this:

arr[0] 0
arr[1] 1
arr[2] 2
arr[3] 3
arr[length] 4 
arr[byteLength] 16
arr[byteOffset] 0 
arr[buffer] 
ArrayBuffer {byteLength: 16, slice: function}
arr[subarray] function subarray() { [native code] }
arr[set] function set() { [native code] } 
arr[BYTES_PER_ELEMENT] 4 
arr[0] 0 
arr[1] 1 
arr[2] 2 
arr[3] 3

 

After doing some research on the internet I came to a conclusion: avoid iterating arrays in JavaScript with for … in syntax and use the long, explicit one instead to get more predictable behaviour. You can try the example yourself.

Enhanced by Zemanta