Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript addition and subtraction with a string value

Tags:

javascript

I recently went through this typecast JS question:

Given '11'+10, the answer is 1110. It is clear that is not 21 because one is a string and JavaScript will treat both as string and perform concatenation instead of mathematical addition.

Why is '11'-10 is equal to 1, instead of something else?

like image 333
arun Avatar asked Jan 21 '26 15:01

arun


1 Answers

Because the subtraction operator is not ambiguous and is only defined for numbers. Hence both operands are converted to numbers first.

See the specification:

  • Addition
  • Subtraction
like image 139
Felix Kling Avatar answered Jan 24 '26 04:01

Felix Kling