๐ŸŽ“ A1Learner
๐Ÿ”

JavaScript Numbers

A JavaScript number is any numeric value. Whole values and decimal values share this one type.

Whole and decimal

A JavaScript number is any numeric value, whole or decimal. The last value uses exponent form, a short way to write large values.

let count = 7;
let price = 19.99;
console.log(count);
console.log(price);
console.log(1e6);

A decimal surprise

Adding decimals can leave a tiny error in the result.

console.log(0.1 + 0.2);

Not a number

NaN is short for not a number, and it marks a failed calculation. Joining the value to a label with + turns it into text, so the console shows NaN itself.

console.log("Result: " + (0 / 0));
console.log(Number.isNaN(0 / 0));
console.log("Result: " + ("abc" * 2));

Example

let price = 2.5;
let quantity = 4;
console.log(price * quantity);
console.log(0.1 + 0.2);
console.log("Check:", Number.isNaN(0 / 0));

Key points

  • Exponent form is a short way to write very large or very small values with the letter e.
  • Decimal values are approximations, so a sum can carry a tiny error.
  • NaN means not a number, and it is the result of an impossible calculation.
  • Dividing a positive number by zero gives Infinity, a value beyond every finite number.
  • Number.isNaN checks whether a value is NaN and reports true or false.

In this example, the program multiplies a decimal price by a whole quantity and prints 10. It then adds 0.1 and 0.2 and prints the approximate result. The last line checks 0 divided by 0 with Number.isNaN and prints true.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does 0.1 + 0.2 print?