Today I've had to take a break from debugging my code to debug my debug messages. Consider:
let x = 1;
console.log('x is ' + x + ' and x-1 is ' + x-1);
// ^^^
// 'NaN'
I get why this happens: by the time we get to the subtraction, x is already a string, and it makes no sense to subtract an integer from a string. (But if x gets multiplied by 2 instead, the result is the intuitively correct 2
; and when you add an 1 to x, you get 11
, also understood).
The question is, is there a way to avoid or work around this behavior, since there is no sprintf()
equivalent in JavaScript? In my case x was a loop index and an array index and it took me a moment to catch why my console.log statements were showing nonsense.