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

2

u/AlGoreBestGore Jun 20 '16

While this is trippy, when would you need to check if null's type is undefined?

0

u/[deleted] Jun 20 '16

[deleted]

1

u/55704841711534631249 Jun 20 '16

That fix stops working if you set the loop to 100,000 cycles (at around the 12k mark)

function foo(bar) {
    return typeof bar === "undefined";
}  
var baz = null;
for(var i=0; i<100000; ++i) console.log(foo(baz))
12291 false VM1493:5
87709 true  VM1493:5 
undefined

https://postimg.org/image/sdwp5ttcn/ https://s31.postimg.org/t3fhi6tw9/failcase1.png

A better fix would be to add true to the expression inside the function:

function foo() {
  return typeof(null) === "undefined" + true;
}

for(var i=0; i<100000; i++) console.log(foo())
100000 false VM1494:5
undefined

https://postimg.org/image/gctc5qm9z/ https://s31.postimg.org/c3om3kj0p/wincase1.png

This is on OS X 10.11.5, Chrome 51. I haven't tested it on Windows, so YMMV.

6

u/leesusmusic Jun 20 '16 edited Jun 21 '16

Am I missing something? "undefined" + true will evaluate to "undefinedtrue", no?