This question is not seeking developer code formatting opinions. Personally, I prefer to use scientific notation in my JS code when I can because I believe it is more readable. For me, 6e8
is more readable than 600000000
. That being said, I am solely looking for potential risks and disadvantages specifying numbers in scientific notation in JS. I don't see it often in the wild and was wondering if there is technical reasoning for that or if it simply because of developer's druthers.
You don't see scientific notation "often in the wild" because the only numbers that actually get typed in JS tend to be constants:
Neither of these benefit from scientific notation too much.
I have seen Plank's constant 'in the wild' as:
const h = 6.62607004e-34;
console.log('Plank', h);
The other place it often makes sense is time limits, for instance the number of ms in a day as 864e5
. For instance:
function addDaysToDate(date, days) {
if (days === 0)
return date;
date.setTime(864e5 * days + date.valueOf());
return date;
}
const now = new Date();
const thisTimeTomorrow = addDaysToDate(now, 1);
console.log('This time tomorrow', thisTimeTomorrow);
I don't think there's any technical reason not to use this notation, it's more that developers avoid hard coding numbers at all.
I don't think there are any risks. You may have to be careful with numbers in strings, but if you're doing that then this syntax is a far smaller issue than, say, number localisation (for instance a DE user entering "20.000,00"
, expecting 2e4
, but getting 2e6
thanks to invariant number formatting swapping the thousand and decimal separators).
I'd add that JS will output that syntax by default anyway for small numbers, but avoids for large numbers up to a point (which varies by browser):
console.log('Very small', 1234 / 100000000000)
console.log('Large, but still full in some browsers', 1e17 * 1234)
console.log('Large, scientific', 1e35 * 1234)