0

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.

Community
  • 1
  • 1
Marek Jedliński
  • 7,088
  • 11
  • 47
  • 57
  • 6
    Surround `x-1` in parentheses. Your issue is operator precedence. – 4castle Apr 22 '17 at 18:39
  • Why, of course it is! Would you post it as a reply? Thanks! – Marek Jedliński Apr 22 '17 at 18:40
  • 1
    don't concat the strings: `console.log('x is', x,'and x-1 is', x-1)` or [Using_string_substitutions](https://developer.mozilla.org/en-US/docs/Web/API/console#Using_string_substitutions) `console.log('x is %o and x-1 is %o', x, x-1);` – Thomas Apr 22 '17 at 18:56

0 Answers0