Table of Contents

  1. Table of Contents
  2. Introduction
  3. Numeric Types in JavaScript
  4. JavaScript Numbers
  5. Scientific Notation
  6. Numbers & Strings
  7. Precision
  8. NaN (Not a Number)
  9. Infinity & -Infinity
  10. Hexadecimal

Introduction

Numbers are the building blocks of programming logic. Themselves being so simple, natural, and metaphysical, they prevade almost all programming tasks. In this tutorial, we’ll discuss how numbers are used in the JavaScript programming language.

Numeric Types in JavaScript

JavaScript has two numeric types: Number and BigInt.

JavaScript Numbers

Unlike many other programming languages, JavaScript has only one type of number that is, number, itself. Since JavaScript has dynamic types, any variable can be used to hold a certain data type such as number:

const food_items = 13;

Scientific Notation

You can also use scientific notation to store numbers conviniently which would otherwise be difficult to maintain in plain notation. Here’s how you do it:

const microorganisms_in_jelly = 7.89e13;    // 78900000000000
const tiny_share = 9.7e-6;                  // 0.0000097

Numbers & Strings

What happens if you add a number and a string? String Concatenation.

1 + "2" // 12
1 + 2 + "3" // 33, since the JavaScript interpreter works left to right

Precision

In JavaScript, integers are only precise up to 15 digits.

99999999999999999999999999999999 // 1e+32
98989898989898998989899898989898989898989898989898989 // 9.8989898989899e+52

NaN (Not a Number)

NaN is a special value of Number, despite not being a number. This property indicates that the value is not legally a mathematical number. These cases show when it’s returned:

99 / "two" === NaN          // true
Math.sqrt(-1) === NaN;      // true
parseInt('number') === NaN; // true
parseInt('NaN') === NaN;    // true
parseInt(NaN) === NaN;      // true

Note:

NaA === NaN         // false
Number.NaN === NaN; // false
// And
99 / "2" === NaN    // false

NaN is rarely used in writing a program.

Infinity & -Infinity

In JavaScript, Infinity and -Infinity are special values of Number. Positive infinity is greater than any other number including, Infinity, itself. The JavaScript infinity behaves similar to the mathematical infinity:

Infinity * 3 = Infinity;    // any positive number times Infinity is Infinity
Infinity * -3 = -Infinity;

3 / Infinity = 0;           // any number divided by Infinity is 0
1 / 0 = Infinity;

Note:

Number.POSITIVE_INFINITY ===  Infinity;    // true
Number.NEGATIVE_INFINITY ===  -Infinity;   // true

Hexadecimal

Numbers are, by default, decimal in JavaScript. To have a hexadecimal number, just precede it with 0x:

0x66 === 102;   // true
0x4 === 4;      // true
oxFA === 250;   // true