AI Hints
Home›JavaScript Tutorial›Names, Numbers and Strings
JavaScript · Lesson 8 of 138

Numbers

Maths in JavaScript.

⏱ 2 min read▶ Video at 7:54🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

JavaScript has one type for all numbers, whole numbers and decimals alike. And it can do all the usual maths, plus a few handy extras.

Numbers
From the video: Numbers
  • One number type
  • Whole and decimal
  • All the usual maths

Arithmetic

Plus, minus, times with a star, and divide with a slash. The percent sign gives the remainder after dividing, so ten percent three is one. Two stars mean to the power of. And brackets control the order, just like in school maths. Run it.

app.jsjavascript
console.log(7 + 3, 7 - 3, 7 * 3, 7 / 2);
console.log("remainder:", 10 % 3);
console.log("power:", 2 ** 10);
console.log("order:", 2 + 3 * 4, (2 + 3) * 4);
Output
10 4 21 3.5
remainder: 1
power: 1024
order: 14 20

Decimal surprises

Computers store decimals in binary, so some simple decimals can't be stored exactly. Zero point one plus zero point two isn't exactly zero point three. Run it. To show a tidy number, use to fixed, with the number of decimal places you want. And dividing by zero gives a special number, Infinity.

app.jsjavascript
console.log(0.1 + 0.2);
console.log((0.1 + 0.2).toFixed(2));
console.log(10 / 0);
Output
0.30000000000000004
0.30
Infinity

Summary

JavaScript numbers do arithmetic, remainders, and powers. Decimals can be slightly off, so use to fixed to display them. Next, text, with strings.

Key takeaways
  • + − * / % **
  • Brackets first
  • toFixed for display
Next up: Strings — text in quotes