Reputation: 83
console.log("1" - - "1" );
Why does the code give me the folloing output: 2
Upvotes: 2
Views: 92
Reputation: 28
This is just two strings being cast as numbers and subtracted. Essentially:
1 - -1
Or 2.
console.log(1 - - 1);
console.log("1" - - "1");
for reference Auto-type conversion in JavaScript
Upvotes: 1
Reputation: 1
Another explanation besides the ones above is that JS has 'forced type conversion', and your expression is essentially trying to subtract a string from another string.
Try a method that converts the strings to numbers so you have more control over the type conversion and the output is more in-line with what you're expecting.
Upvotes: 0
Reputation: 10096
Well, if you subtract -1 from 1 you get 2, simple math, and that's what JavaScript does too.
JavaScript converts the strings you give it into numbers and then runs the calculation.
console.log(1 - - 1);
console.log(1 - - 2);
console.log(1 - - 3);
console.log(1 - - 155);
Upvotes: 0
Reputation: 10458
this string is equivalent to
1 - (-1)
since javascript converts the string to numbers for you try running the code snippet
console.log(- "1");
console.log(1 - "1");
console.log(1 - - "1");
console.log("1" - - "1");
Upvotes: 0