DateTime Math Works with 2 lines of code but not one

Viewed 34

I've come across an interesting Javascript phenomenon that I can't explain. Let's say I wanted to convert the current time into values ranging from 0.0 to 23.5, in 0.5 increments - ie. 0, 0.5, 1 1.5 ... 22, 22.5, 23, 23.5

This code does that:

const dateTimeNow = new Date();
let currentTime = dateTimeNow.getHours();
currentTime += (dateTimeNow.getMinutes() === 30) ? 0.5 : 0;
console.log(currentTime);

But this single line version fails to produce the correct value:

const dateTimeNow = new Date();
let currentTime = dateTimeNow.getHours() + (dateTimeNow.getMinutes() === 30) ? 0.5 : 0;
console.log(currentTime);

Hoping someone can explain why!

2 Answers

The reason is operators' precedence. Your expression:

a + b ? c : d

Evaluates to:

(a + b) ? c : d

And NOT to:

a + (b ? c : d)

It's your ternary operator, you thing that order of operations should go like this:

dateTimeNow.getHours() + (dateTimeNow.getMinutes() === 30) ? 0.5 : 0;

dateTimeNow.getHours() + 0.5

20.5

In reality, it does this:

dateTimeNow.getHours() + (dateTimeNow.getMinutes() === 30) ? 0.5 : 0;

20 + true ? 0.5 : 0;

21 ? 0.5 : 0;

0.5;

To fix this you just need to add another set of parentheses:

let currentTime = dateTimeNow.getHours() + ((dateTimeNow.getMinutes() === 30) ? 0.5 : 0);

Related