I have a 2D array with 2 values and I want to print the difference with a little message.
var array = [[0,2],[3,4]];
console.log(array[0][1]-array[0][0]) //prints '2'
console.log(array[0][1]-array[0][0] + ' is the number') //prints '2 is the number'
console.log('The number is' + array[0][1]-array[0][0]) //prints 'NaN'
console.log('The number is ' + parseInt(array[0][1]-array[0][0], 10)) //prints 'The number is 2'
Why do I need to parseInt() here to print a message before the result, but printing text after the result, or just the result on its own, is A-OK?
Actually, the
parseIntmakes no difference. It’s putting the subtraction in parentheses that matters.What your code is basically saying is:
It’s all about order of operations.