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?
Adding Numbers and StringsJavaScript uses the + operator for both addition and concatenation. Numbers are added. Strings are concatenated.
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.
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.
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.
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.
(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With