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]

-4

u/hkrdrm Jun 20 '16

still wouldn't it be more proper to check

if(some_variable === null)

13

u/StoneCypher Jun 20 '16

no. null is a placeholder here.

what he's saying is "if you compare things to typeof undefined, every hundred or so iterations it'll fail. look, it even happens with null."

-8

u/hkrdrm Jun 20 '16

I get that but what I'm saying if you have some function and i want to know if the argument is null wouldn't it make more sense to check it like this

function foo(my_arg) {
  if(my_arg === null){
    console.log("arg is null here insert logic for null case here.");
  }
}

I'm not getting why anyone would need to check type equal to undefined.

14

u/StoneCypher Jun 20 '16

Because he's not checking if it's null, and you can't actually strict-equals compare to undefined in this language in a bunch of common circumstances.

It is very common to have to check if something is undefined. By example, if you retain a JSON object from an API, and you want to check whether the server actually set some or another value, before you attempt to use it.

He's talking about the undefined comparison.

I'd like you to stop focussing on null, please. It's beside the point. Thank you

1

u/RReverser Jun 21 '16

and you can't actually strict-equals compare to undefined in this language in a bunch of common circumstances.

Of course you can. The only case where you can't is if you're checking existance of a global variable for feature detection, in all the other cases === undefined works like a charm.