What are integers in JavaScript?

According to the ECMAScript specification, all numbers in JavaScript are floating-point. Yet, the notion of integer comes up occasionally. This blog post explains what it means.



What are integers?



JavaScript has only floating-point numbers. Integers appear internally in two ways. First, most JavaScript engines store a small enough number without a decimal fraction as an integer (with, for example, 31 bits) and maintain that representation as long as possible. They have to switch back to a floating point representation if a number’s magnitude grows too large or if a decimal fraction appears.


Second, the ECMAScript specification has integer operators: namely, all of the bitwise operators. Those operators convert their operands to 32-bit integers and return 32-bit integers. For the specification, integer only means that the numbers don’t have a decimal fraction, and 32-bit means that they are within a certain range. For engines, 32-bit integer means that an actual integer (non-floating-point) representation can usually be introduced or maintained.

Ranges of integers




Internally, the following ranges of integers are important in JavaScript:


  • Safe integers [1], the largest practically usable range of integers that JavaScript supports:

    • 53 bits plus a sign, range (−253, 253)



  • Array indices [2]:

    • 32 bits, unsigned

    • Maximum length: 232−1

    • Range of indices: [0, 232−1) (excluding the maximum length!)




  • Bitwise operands [3]:

    • Unsigned right shift operator (>>>): 32 bits, unsigned, range [0, 232)

    • All other bitwise operators: 32 bits, including a sign, range [−231, 231)




  • “Char codes”, UTF-16 code units as numbers:

    • Accepted by String.fromCharCode()

    • Returned by String.prototype.charCodeAt()

    • 16 bit, unsigned





More blog posts on integers



All blog posts on integers have the label jsint. Converting to integer is covered by two blog posts:


References




  1. Safe integers in JavaScript

  2. Arrays in JavaScript

  3. Label bitwise_ops: blog posts on bitwise operators


Comments

Popular posts from this blog

Steve Lopez and the Importance of Newspapers

Ideas for fixing unconnected computing

Omar to kill me