How is "2" + "2" - "2" = 20 in JavaScript?

I just accidentally played around JavaScript. Input to him '2'+'2'-'2'.

and the conclusion is surprising 20.

console.log('2'+'2'-'2');
Run codeHide result

Now I dont understand.

Can someone explain to me why this is so? How can this value be deduced equal 20?

+6
source share
3 answers

+is both concatenation and addition. If any of the arguments is not numeric, then this is concatenation. Thus, it '2' + '2'is '22'- just like it "foo" + "bar"is "foobar", and just like it 3 + {}is "3[object Object]".

- . , , . , '22' - '2' 22 - 2, 20.

+20

JavaScript +. , "2" "2" "22".

(-) . , "22" 22, "2" 2. 2 22, 20.

: Coercion

:

'2' + '2' - '2' To

'22' - '2' To

22 - 2 To 20

+2

JavaScript coercion.

+ JavaScript , . , JavaScript , ?

, ( +) , JavaScript .

console.log(2 + 2); // 4
console.log('2' + '2'); // '22'
Hide result

, , : .

, JavaScript '22' - 2, 2 "22". , , "22" , JavaScript ( "" ) .

22 - 2, 20, , .

+1

All Articles