I came across this simple exercise on exercism.io, the instructions were:
Calculate the moment when someone has lived for 10^9 seconds. A gigasecond is 10^9 (1,000,000,000) seconds.
The exercise itself was easy enough to solve, one of its primary purpose is to teach students about using well-named constants instead of magic numbers in their code. For this exercise, you need to store the value of a gigasecond, in milliseconds. With a plain number, it would be this:
const GIGASECOND_IN_MILLISECONDS = 1000000000000
Quick, tell me how many zeroes are in that number. Since we're clever mathematicians, we know that there are 12. How? Well, we were told that a gigasecond is 10^9 seconds and we know that to convert seconds into milliseconds we only need to multiply by 1000, or add 3 zeroes at the end. Still, you have to admit that if you knew nothing about gigaseconds, it would be hard for you to know just how big that number is.
const GIGASECOND_IN_MILLISECONDS = 10 ** 12
This necessitates an understanding of basic mathematics but I think it’s safe to assume that the vast majority of people that will be reading or modifying your code will know about exponents.
I like this one. If you want to get technical, this also involves maths and exponentiation.
const GIGASECOND_IN_MILLISECONDS = 1e12
This is basically like saying, “1 times 10 raised to the power of 12.” So the
e here is a stand-in for “times 10 raised to the power of.” What I like about it, since we're working in the decimal system, is that you can think of it simply as “1 followed by 12 zeroes.”
You can also use it to represent decimals.
15e-4 === 0.0015 12345E-5 === 0.12345
Here too, you can forget about the math and just remember that when the exponent is a negative number, it represents the number of digits after the decimal point. Also, as you can see in the example, you can use lowercase
e or uppercase
const GIGASECOND_IN_MILLISECONDS = 1_000_000_000_000
const fee = 138400
which is meant to represent $1384.00 but it’s far from obvious. Thanks to numeric separators, you can now do this
const fee = 1384_00
Of the three, my favourite has to be the scientific notation but if you want the most readable code at a glance the numeric separator is probably the way to go when dealing with constants.