Adding and subtracting strings and numbers in Javascript - automatic type conversion?

Take a look at the following Javascript code.

<script type="text/javascript" lang="javascript"> function test() { alert('2'+8); alert(8-'2'); } </script> 

The first warning window displays the result of concatenation 2 and 8, which is 28 . In the second warning field, however, it displays the subtraction of two numbers, which are 6 . How?

+4
source share
5 answers

The + operator is overloaded. If any operand is a string, string concatenation is performed. If you have two numbers, the addition is performed. - not overloaded in this way, and all operands are converted to numbers.

From the specification:

11.6.1 Add (+) operator

(...)
7. If Type (lprim) is String or Type (rprim) is String, then

  • Return a string that is the result of combining ToString (lprim), followed by ToString (rprim)

8. Return the result of applying the add operation to ToNumber (lprim) and ToNumber (rprim).
(...)

11.6.2 Subtraction operator (-)

(...)
5. Let lnum be ToNumber (lval).
6. Let rnum be a number (rval).
7. Return the result of the subtraction operation to lnum and rnum.
(...)

+10
source

+ used both to concatenate strings and to add them. If any operand is a string, concatenation is used. - used only for subtraction, both operands are always transferred to numbers.

+3
source

+ used for both concatenation and addition, but when used with a string, concatenation is used by default. - cannot be used for strings, so its operands are converted to numbers.

Edit: this should not match the above message! Xd

+3
source

1st: it translates the 2nd operand into the 1st operand (String), because + is used for concat strings too.

2nd: it distinguishes the 2nd operand from a number, because - it is used only for operations with numbers.

+1
source

If you do not want this, it is easy to fix: (1 * '2') + 8 JSYK

0
source

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


All Articles