Search code examples
javascriptruntimedynamic-languagesv8

If I was a VM how would I treat numbers when executing JavaScript?


I've been thinking about how to best bridge the gap between CLR world (.NET runtime) and JavaScript and one thing that came to mind was this notion of a type in JavaScript that it is somewhat inferred from the usage while i.e. C# doesn't need to do this.

I'd like to know a little more about the implementation specifics of JavaScript engines specifically regard how your treat a number. The standard outlines a series of operations that are valid in certain contexts and yields certain specific results, strictly speaking, the concept of an integer doesn't exist in JavaScript but there are typical integer arithmetic operations such as bit shift (>>) which always operate on a 32-bit signed integer and always yields a 32-bit signed integer.

I guess the hard part is figuring out when a number is an integer and when a number isn't an integer. But how does VMs do this?

var x = 1; // is this an integer or a double?
var x = 1.0; // is this an integer or a double?
var x = 2147483648; // is this an integer or a double?
var x = 9007199254740993; // is this an integer, double or runtime error?

I'm guessing there's a lot of heuristics that goes into this. I'm specifically looking for some underlying theme that can be sort of used to better reason about these things.

Also from a performance perspective if you realizes that certain numbers are used as integer you can absolutely optimize those situations by sticking to integers. Though, how do you know when to do this?

Any JavaScript VM gurus out there who'd like to take a stab at this? (at this point I'm more interested in the internals of the VM than the actual specifics of the specification)


Solution

  • If you want to get into the nuts-and-bolts of how JavaScript implementations handle the Number type, there's nothing like going to the source. I'd look at: