var x = "016"; var y = 0|x; console.log(y); // 16 var x = "0o16"; var y = 0|x; console.log(y); // 14 console.log(016); // 14 console.log(0o16); // 14
This example works differently in ECMAScript 3 and ECMAScript 5, as beautifully explained by CMS on StackOverflow.
This is what you’d see if you were skimming through the recent re-introduction article:
If you’re in a hurry, you’ll probably not see the important bit of text immediately following the examples:
Here we are setting up two variables. The assignment in the middle part of the for loop is also tested for truthfulness — if it succeeds, the loop continues. Since i is incremented each time, items from the array will be assigned to item in sequential order. The loop stops when a “falsy” item is found (such as undefined).
Note that this trick should only be used for arrays which you know do not contain “falsy” values (arrays of objects or DOM nodes for example). If you are iterating over numeric data that might include a 0 or string data that might include the empty string you should use the i, len idiom instead.
For a clear example of the problem, consider this code that uses the “nicer idiom” in the wrong way:
The issue here is that the array must not contain falsy values. This includes undefined values in sparse arrays, null, zero,
document.all, or any other values that coerce to false. The proper way to iterate over an array is to explicitly visit every index unless you have a clearly defined and documented reason not to continue through the array.