Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's look at the following Javascript code.

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

In the first alert box, it displays the result of concatenation of 2 and 8 which is 28. In the second alert box, however it displays the subtraction of two numbers which is 6. How?

like image 801
Lion Avatar asked Nov 14 '11 01:11

Lion


People also ask

Can you add numbers and strings in JavaScript?

Adding Numbers and StringsJavaScript uses the + operator for both addition and concatenation. Numbers are added. Strings are concatenated.

Can we convert string value into number in JavaScript?

How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.

How do you convert a string to an integer in JavaScript?

In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.

How do you subtract a value in JavaScript?

Similarly, we use the minus sign ( - ) to subtract numbers or variables representing numbers. We can also add and subtract with negative numbers and floats (decimals). One interesting thing to note and be aware of in JavaScript is the result of adding a number and a string.


1 Answers

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

From the specification:

11.6.1 The Addition operator ( + )

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

  • Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)

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

11.6.2 The Subtraction Operator ( - )

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

like image 163
Felix Kling Avatar answered Oct 07 '22 10:10

Felix Kling