Numbers
JavaScript has one number type for whole numbers and decimals alike, which keeps things simple until decimals surprise you.
One number type covers integers and floats. Decimal arithmetic is approximate because of binary storage, so 0.1 + 0.2 is not 0.3. NaN is a number that means the arithmetic failed.
EXERCISE
1One Number Type for Everything
Unlike most languages, JavaScript does not separate whole numbers from decimals, which removes a whole category of decisions.
There is no int, no float, no double. There is number, and it holds all of them.
Whole, decimal, negative, all the same type:
const count = 7;
const price = 7.99;
const debt = -250;
const tiny = 0.000001;
console.log(typeof count, typeof price, typeof debt, typeof tiny);
// number number number number
The arithmetic you would expect:
console.log(10 + 3); // 13
console.log(10 - 3); // 7
console.log(10 * 3); // 30
console.log(10 / 3); // 3.3333333333333335
console.log(10 % 3); // 1 remainder after dividing
console.log(10 ** 3); // 1000 ten to the power of three
Note 10 / 3. In a language with an integer type that would be 3. Here, division always produces a full decimal.
Two special numbers you will meet:
console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity
console.log("abc" * 2); // NaN "Not a Number"
console.log(typeof NaN); // "number" <- yes, really
// NaN is the answer when arithmetic was attempted and failed.
// It is a number in the same way that a blank cheque is a cheque.
NaN is the only value in that is not equal to itself, so NaN === NaN is false and comparing against it never works. Use Number.isNaN(value) when you need to check. You will hit this the first time a form gives you text where you expected a number.
EXERCISE
2Why 0.1 + 0.2 Is Not 0.3
This is the single most surprising thing about numbers in JavaScript, and it is not a bug in the language.
Computers store numbers in binary, and some perfectly ordinary decimals have no exact binary form, in the same way that one third has no exact decimal form.
See it for yourself:
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
console.log(0.3 - 0.1); // 0.19999999999999998
console.log(1.005 * 100); // 100.49999999999999
Why: one third in decimal has the same problem:
// 1/3 in decimal = 0.3333333... forever.
// Write it down with 10 digits and you have an approximation.
// 0.1 in binary = 0.000110011001100... forever.
// Store it in 64 bits and you have an approximation.
// Add two approximations and the error becomes visible.
// This affects Python, Java, C and Go identically. It is not a JS flaw.
What to do about it:
// 1. Never compare decimals with ===. Compare within a tolerance.
const almostEqual = Math.abs(0.1 + 0.2 - 0.3) < 0.000001;
console.log(almostEqual); // true
// 2. Round for display.
console.log((0.1 + 0.2).toFixed(2)); // "0.30" note: a STRING
// 3. For money, work in the smallest unit as whole numbers.
const priceInPaise = 1999; // not 19.99
const totalInPaise = priceInPaise * 3;
console.log(totalInPaise / 100); // 59.97 only at the very end
Pro Tip: The money rule matters in real work. Store and calculate currency as whole numbers of the smallest unit, paise or cents, and convert only when you display it. Every payment system does it this way, and now you know why.
EXERCISE
3Turning Text into Numbers
Anything a person types arrives as text, so converting it correctly is a daily task rather than an edge case.
An input box always gives you a string, even when the person typed digits. "5" + 1 is "51", and that bug has shipped in production more times than anyone would like to admit.
Three ways to convert, with different tempers:
console.log(Number("42")); // 42
console.log(Number("42.5")); // 42.5
console.log(Number("42abc")); // NaN <- strict: all or nothing
console.log(Number("")); // 0 <- watch this one
console.log(parseInt("42abc")); // 42 <- lenient: reads what it can
console.log(parseFloat("42.5x")); // 42.5
console.log(parseInt("abc")); // NaN
The plus trick, which you will see in other people's code:
console.log(+"42"); // 42
console.log(+"42abc"); // NaN same rules as Number()
// Short, and clear once you know it. Use Number() while learning.
The bug this prevents:
const typed = "5"; // from an input box
console.log(typed + 1); // "51" string concatenation!
console.log(Number(typed) + 1); // 6 what you wanted
// Only + is ambiguous. The others convert for you:
console.log(typed - 1); // 4
console.log(typed * 2); // 10
Pro Tip: Convert at the boundary. The moment a value arrives from an input, a URL or an API, turn it into the type you actually want and keep it that way. Sprinkling
Number()calls deep inside your logic means you are converting the same value over and over and still not sure what type it is.
