r/javascript • u/ziriax • Jun 20 '16
Javascript developers, be warned about this crazy JIT bug in V8!
Last week I've spent a full day to fix very strange behavior in a single page application for my customer that only happens on Chrome 51 (maybe 52, but not in Canary 53).
After a while our SPA started behaving incorrectly...
It turned out to be a nasty bug in the V8 JIT engine.
Try the following in Chrome's developer console:
function foo() {
return typeof null === "undefined";
}
for(var i=0; i<10000; ++i) console.log(foo())This should of course always print false, but in Chrome 51, it prints true after about about 100 iterations (it varies...)
I want to warn other web-developers for this bug, to avoid many $$$ being wasted (or becoming insane ;-))
EDIT: The following - more realistic case that we had in third-party library code - will also fail, but after about 10 thousand iterations:
function isUndefined(thing){
return typeof thing === "undefined";
}
for(var i=0; i<100000; i++) console.log(isUndefined(null));
EDIT: The bug also manifests itself with the more common pattern
typeof x !== "undefined"UPDATE: I just tried this with the latest stable Chrome (52.0.2743.82), and it now works correctly :)
2
u/qwzxercv Jun 22 '16 edited Jun 22 '16
With modern JS development for the web, you definitely should not just throw global variables around on the page and hope that they exist. You should be using a module system to help mitigate this issue, which renders this discussion moot.
However, if you really need to rely on global variables, they do exist as properties on window, so if you need to check for its existence, you should check for
if (window.foo !== undefined) { ... }instead.I see no valid reason to be concerned about the existence of global variables when you shouldn't even be using global variables anyways.