- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Numbers
JavaScript Numbers & Math
JavaScript Numbers
JavaScript has a single number type covering both whole numbers and decimals.
There is no separate integer type, unlike most other languages.
Every number is stored the same way, which explains several of its quirks.
Example
Example
javascript
const whole = 42;
const decimal = 3.14;
console.log(typeof whole);
console.log(typeof decimal);Both report number.
One Number Type
42 and 3.14 are both of type number.
Numbers are written without quotes.
Very large or very small numbers can use exponent notation.
Syntax
Syntax
javascript
const count = 42;
const price = 19.99;A number in quotes is a string, not a number.
Arithmetic
The usual operators all work as you would expect.
Example
Example
javascript
console.log(10 + 3);
console.log(10 - 3);
console.log(10 * 3);
console.log(10 / 3);Division always produces a decimal when it does not divide evenly.
Remainder and Power
% gives the remainder, which is how you test for even numbers.
** raises to a power.
Example
Example
javascript
console.log(10 % 3);
console.log(10 % 2 === 0);
console.log(2 ** 10);The output is 1, true, 1024.
Infinity
Dividing by zero gives Infinity rather than throwing an error.
This surprises people coming from other languages.
Example
Example
javascript
console.log(10 / 0);
console.log(-10 / 0);
console.log(typeof Infinity);Infinity is a number value, like any other.
Exponent Notation
e means times ten to the power of.
Example
Example
javascript
const big = 1.5e6;
const small = 1.5e-3;
console.log(big);
console.log(small);The output is 1500000 then 0.0015.
Separators for Readability
Underscores can be used to group digits; they are ignored by JavaScript.
Example
Example
javascript
const million = 1_000_000;
console.log(million);
console.log(million === 1000000);This is purely for people reading the code.
Complete Example
Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Numbers</title>
</head>
<body>
<h1>JavaScript Numbers</h1>
<p id="out"></p>
<script>
const price = 19.99;
const quantity = 3;
document.getElementById("out").innerHTML =
"Price: " + price +
"<br>Quantity: " + quantity +
"<br>Total: " + (price * quantity) +
"<br>Is even: " + (quantity % 2 === 0);
</script>
</body>
</html>Try It Yourself
Run the above example in the Try It Editor.
Try dividing by zero:
Add price / 0 and see Infinity appear.
Important Points
- JavaScript has one number type.
- Integers and decimals are both numbers.
%gives the remainder.- Dividing by zero gives
Infinity, not an error. - Underscores can group digits for readability.
Conclusion
One number type keeps the language simple but causes a few surprises.
Infinity instead of an error is the first of them.
Floating point precision, covered shortly, is the biggest.
