JavaScript Number

JavaScript Number

In JavaScript, number is a primitive data type that represents numeric values. It can be positive, negative, or zero. Numbers can be written with or without decimals.

Creating a Number

There are multiple ways to create a number in JavaScript. The simplest way is to just write a number:

let myNumber = 42;

You can also create a number using the Number() function:

let myNumber = Number("42");

Or by using the parseInt() function to convert a string to an integer:

let myNumber = parseInt("42");

Mathematical Operations

JavaScript provides a variety of mathematical operations that can be performed on numbers. Here are some examples:

  • Addition: let sum = 4 + 5;
  • Subtraction: let difference = 10 - 3;
  • Multiplication: let product = 6 * 7;
  • Division: let quotient = 12 / 4;
  • Remainder: let remainder = 10 % 3;
  • Exponentiation: let result = Math.pow(2, 3); // 2 raised to the power of 3

NaN and Infinity

JavaScript also has two special numeric values: NaN and Infinity.

NaN stands for "Not a Number" and is returned when a mathematical operation fails. For example:

let result = 0 / 0; // NaN

Infinity represents the mathematical concept of infinity. It is returned when a number is too large to be represented by JavaScript. For example:

let result = 1 / 0; // Infinity

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe