12

It seems that JS V8 engine has a bug.

As example you can execute this script in the Chrome console (I use version 51.0.2704.103 m.) and each time you will get random (at first glace) number of true and false values:

    function foo(){
        return typeof null === 'undefined';
    }
    
    for (var i = 0; i<1000; i++) console.log(foo());

For example:

enter image description here

On different OS / systems this bug appears on different iterations.

I realize that this question has little practical sense, but I wonder what causes this strange behavior and depending on what changes the number of iterations?

Also, what should be kept in mind when you write code using typeof null in case of this bug?

Sergey Novikov
  • 4,096
  • 7
  • 33
  • 59
  • Just tried this in Chrome and I'm getting 1000 false's – Teo Nicholas Jun 21 '16 at 09:17
  • 1
    The first time I run the loop, it happens for me as well (133 false, 867 true). Subsequent calls of the loop always yield 1000 true, though. – robertklep Jun 21 '16 at 09:19
  • @robertklep Not if you redefine the function each time. Subsequent calls to the same function will print 1000× `true`… – feeela Jun 21 '16 at 09:24
  • @feeela yeah, redefining the function will always yield both true and false results. – robertklep Jun 21 '16 at 09:24
  • Tried on 3x Windows PC (always random results) and 1x MAC (more consistent results, but still random). – Sergey Novikov Jun 21 '16 at 09:25
  • 1
    @robertklep I consistently get the first 132 false `for (var i = 0; i<132; i++) foo();` and everything after that true – user2314737 Jun 21 '16 at 09:26
  • @user2314737 same on MAC, but after several tries count of false results changes. – Sergey Novikov Jun 21 '16 at 09:28
  • @user2314737 same here, if I reopen new tabs tho, I get different random results – Mario Garcia Jun 21 '16 at 09:37
  • 1
    Node v6 also exhibits the same behaviour (random results). Node v4 doesn't. So my guess is that it's a recent V8 issue. – robertklep Jun 21 '16 at 09:47
  • On my mac threshold is 12291. It and everything bellow it behaves normal but if 12292 then i get one true. Any consecutive call to function prints all true values. This is quite weird – Rouz Jun 21 '16 at 10:12
  • I always get false returned, and I went up to 100,000 iterations. I'm using an old version of chrome though, version 49.0.2623.87 m. – bastos.sergio Jun 21 '16 at 10:45
  • 3
    For reference, it's an [already fixed bug](https://github.com/v8/v8/commit/7dfb5beeec8821521beeb2b8eac36707a663064c) in the V8 jitter. Posting as a comment only, as I don't know enough about the innards to explain _why_ it's happening. – James Thorpe Jun 21 '16 at 11:22
  • I've tried in chrome and got strange result, but the same thing works perfectly fine on node ( tried on version 5.10.1) – SzymonPoltorak Jun 22 '16 at 15:40

0 Answers0