Amazing simple operation results

In JavaScript, I tried to follow the instructions below

var x = 1+"2"-3; //Anser is 9.
var y = 1-"2"+4 //Anser is 3.

For such operations is converted to which?

I think, 1+"2" = 12(number)then 12-3?

+4
source share
2 answers

-converts both operands to numbers. But if either operand in +is a string, the other is converted to a string and represents concatenation. Like "Hi, " + "how are you?" = "Hi, how are you?"So, your answers are correct.

var x = 1+"2"-3; 
// concats the string as 12 and then subtracts...
12 - 3 = 9
var y = 1-"2"+4 
// converts to numbers and subtracts, making -1 and then adds 4 giving out 3
-1 + 4 = 3

It was a process.

+3
source

Scenario I

Step 1:

1 + "2" => "12" //concatenation happened

Step 2

"12" - 3 => 9 //String widens to number since we are using - symbol here.

Scenario II

Step 1:

1 - "2" => -1 //String widens to number since we are using - symbol here.

Step 2:

-1 + 4 => 3 //Normal addition happens
+2
source

Source: https://habr.com/ru/post/1545496/


All Articles