r/javascript • • 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 :)

482 Upvotes

117 comments sorted by

View all comments

1

u/[deleted] Jun 20 '16

So if you run it with the console.log in the loop all of them evaluate false

for(var i=0; i<10000; ++i) console.log(typeof null === 'undefined')
// 10000 false

But if you change the var to a let and run the console.log right in the loop it's almost 50/50 split

for(let i=0; i<10000; ++i) console.log(typeof null === 'undefined')
//4917 false
//5083 true

1

u/RReverser Jun 21 '16

Perhaps you were just running in the DevTools console and not as a script - that would result in a different behavior as in the first case you're introducing a global variable (aka window.i).

1

u/[deleted] Jun 21 '16 edited Jun 21 '16

Shouldn't matter the variable isn't even used, regardless if you wrap each of those in an IIFE the result is the same.

1

u/RReverser Jun 30 '16

It does matter because in one case it's just local variable which can be optimized away, while in another it's a property access on a global object which can't be - very different operations, with different handling and performance.

1

u/[deleted] Jun 30 '16

As I said I've put this in an IIFE, effectively making a local variable, and the behaviour was the same.