Mastering JavaScript Numbers

JavaScript numbers are a fundamental data type used to represent both integer and floating-point values. Understanding how to work with numbers is essential for performing mathematical operations, comparisons, and handling numerical data in web development. JavaScript provides a single Number type for all numeric values, with the ability to represent integers, floating-point numbers, and special values such as NaN (Not-a-Number) and Infinity.

How to work with JavaScript numbers

You can declare a number in JavaScript simply by assigning a value to a variable:

let integerExample = 42; let floatingPointExample = 3.14;

JavaScript also supports scientific notation for very large or very small numbers:

let smallNumber = 1e-5; // Equivalent to 0.00001 let largeNumber = 2e6; // Equivalent to 2000000

Arithmetic operations

JavaScript supports all standard arithmetic operations, including addition, subtraction, multiplication, division, and modulus (remainder):

let sum = 10 + 5; // 15 let difference = 10 - 5; // 5 let product = 10 * 5; // 50 let quotient = 10 / 5; // 2 let remainder = 10 % 3; // 1

Special numeric values

JavaScript's Number type includes several special values:

  • NaN (Not-a-Number): Represents a computational error or an undefined mathematical result.
let result = 0 / 0; // NaN
  • Infinity and Infinity: Represent values beyond the largest and smallest representable numbers.
let positiveInfinite = 1 / 0; // Infinity let negativeInfinite = -1 / 0; // -Infinity

Checking for number type

To check whether a value is a number, use the typeof operator or Number.isFinite for distinguishing real numbers from Infinity, -Infinity, and NaN:

typeof 42; // "number" Number.isFinite(1 / 0); // false

Parsing numbers from strings

To convert a string to a number, use parseInt, parseFloat, or the unary + operator:

parseInt("123"); // 123 parseFloat("10.5"); // 10.5 +"42"; // 42

Understanding and effectively using numbers in JavaScript is crucial for any web development project. Whether you're calculating values, formatting numbers for display, or interpreting numeric input from users, JavaScript's Number type and its associated methods provide a robust foundation for numerical operations.

Invite only

We're building the next generation of data visualization.