I've been writing a lot of time related code recently, and in various files, I always end up re-defining things like

var SECOND = 1000; var MINUTE = 60 * SECOND;

This gets frustrating quickly. So I'm considering two possibilities:

  1. Getting rid of the constants and instead letting things be inferred from code like 60 * 1000
    • I dislike this option because it's not as human readable
  2. Attaching the constants to a global so they only have to be written in one place
    • I think this is the best way to go, but I'm unsure about the potential consequences of this
  3. I could use a package and import from it
    • This has the same problem that I'm already doing, which would be defining it everywhere over and over

How do you handle this issue or is it something we have to live with?

Side note 1: I am writing this in JavaScript, which is why globals are an option, but I feel like this might still be applicable to other languages

Side note 2: Specifically for JavaScript, why are these constants not already attached to the global objects browser/globals?

  • 3
    Possible duplicate of Eliminating Magic Numbers: When is it time to say "No"? – gnat Jan 24 '17 at 17:18
  • What's wrong with using Javascript Date objects? – Erik Eidt Jan 24 '17 at 18:23
  • Be careful with using constants for time like this. Not every minute has 60 seconds. – zzzzBov Jan 24 '17 at 19:22
  • C# for example has a TimeSpan which encapsulates the unit and the value. For JavaScript, perhaps checkout the moment.js library, which is useful for managing time. – Matthew Jan 24 '17 at 20:21
  • @ErikEidt I'm using this for things like setTimeout(someFunction, 10 * SECOND), so Date objects won't work for that. Same answer applies to using moment, @Matthew, which I am using for other functionality, but it does not have constants – Merlin -they-them- Jan 24 '17 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.