I have a factory that creates a new entity and it calls new Date() multiple times to fill multiple fields like shown below:
dateJoined: format('yyyy-MM-dd')(new Date()),
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
one of my senior engineers suggested saving new Date() in a const and using it instead of calling new Date() multiple times, so the above code would change to be like this:
const date = new Date();
dateJoined: format('yyyy-MM-dd')(date),
createdAt: date.toISOString(),
updatedAt: date.toISOString()
He mentioned that one of the reasons for calling new Date() one time only is that there might be a millisecond difference between dates if we call it multiple times.
I am curious how likely is that to happen? and are there other benefits to calling new Date() one time only?
I tried it in my browser using this script:
and there are some iterations where the three dates are not equal. Typically, around 8 per 10000.
This is exactly the kind of inconsistency that passes many test runs but almost inevitably will bite you in production. Avoid it and follow your senior's advice.