New to Javascript and something that I came across was kind of interesting. I was shown this example:
"37" - 7 // "30"
"37" + 7 // "337"
This was an exercise to show how Javascript converts and handles strings and integers. What I don't understand is why these two statements are handled differently. The first statement will convert 37 to an integer and subtract 7, leaving 30 (if I change it to 6, it becomes 31). However, in the second statement, it treats it like a string and concatenates the second 7 onto the end of the string.
For testing purposes, I am writing this:
var number = "37" - 7
console.log(number);
in a text, saving it as a .js file and executing it with Node.js.
If there is no easy way to explain this, I will just chalk this up to a bizarre behaviour that JS has. An over-complicated answer would be wasted on a newbie like me.
Thank you in advance.
+is used both for addition and concatenation, whereas-is just minus. In your case you're concatenting strings with the+.