Using e3 notation to represent seconds in JavaScript

Sept 02, 2024

When dealing with amounts of time in JavaScript, it is very common to use milliseconds. The native functions that accept an amount of time as a parameter (e.g. setTimeout, setInterval) take milliseconds, and your functions should too.

The annoying part about working with milliseconds is that often times, the timespans you're dealing with are in seconds. Meaning, it's very common to want to run a function in 30 seconds, for example. In that case, you're stuck passing in 30000:

setTimeout(() => doSomething(), 30000);

This works, and it's not a huge deal, but it is error-prone. The more 0s we put next to each other, the more difficult it becomes to make sure we have the correct number. Visually 30000 and 300000 don't look that different.

Scientific Notation to the Rescue

Although you don't often see it used in the wild, JavaScript has built-in support for scientific notation. As an example:

console.log(2e3);
// 2000

2e3 is the equivalent of writing out 2 * 10**3, which is the equivalent of 2 * 1000, hence 2000 is logged.

So what can we do with this?

Because a second is 1,000 seconds, we can use e3 notation to represent seconds within our codebase. Let's go back to the original example but use e3 notation instead:

setTimeout(() => doSomething(), 30e3);

Sooo much easier to read, and much less error prone as well.

I have introduced this notation into several code bases that I have worked on, and it provides great clarity. Any time I see e3 I know that the value that I am looking at represents seconds.

Of course that does not have to be true, you could use e3 notation (or e2, e4, etc.) anywhere you'd like. But I have found that using it only when you want to represent seconds to be most effective.