Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 1 + '1' = '11' but 1*'1' = 1 [duplicate]

Tags:

javascript

In case of operation

1 + '1',

the number 1 is converted to string and appended to the later string then why isn't it the case for

1 * '1'

like image 546
Pawan Avatar asked Jul 31 '14 10:07

Pawan


People also ask

Is 01 and 1 the same?

There is no difference between the numbers 01 and 1 . They are absolutely identical.

Why addition is not working in JS?

1 Answer. This happens when one or both of the variables is String which results in string concatenation. The arithmetic operators like / * - performs a toNumber conversion on the string(s). In order to convert a string to a number : use the unary + operator.

What is number method in Javascript?

The Number() method converts a value to a number. If the value cannot be converted, NaN is returned.


2 Answers

Because + is overloaded.

+ can mean either addition or string concatenation. In the former case, JavaScript attempts to do string concatenation rather than addition, so it converts everything to a string and carries out the string concatenation. In the latter case, the only option is to multiply, so it converts everything to something that can be multiplied and carries out the multiplication.

dfsq linked the specification of addition syntax in the comments under your question, which explains why JS attempts string concatenation instead of addition: It checks whether the things you're adding together are strings, and then if at least one of them is, attempts string concatenation - and otherwise, attempts addition.

like image 116
Matthew Avatar answered Oct 16 '22 23:10

Matthew


The + is a concatenation operator for strings. As a result, the number gets converted to a string and then concatenated. The concatenation takes preference over numeric addition. If you want to make it add them instead, use parseInt, like 1 + parseInt('1')

The * is not a valid operator for strings at all, so it converts the string to a number and then does the operation.

This is a simple case, so the order of operands don't matter. If you get more complex, it tends to get even more interesting. For instance:

1 + 1 + '1' = '21'
'1' + 1 + 1 = '111'

For more information, check out this MDN article on the matter

like image 31
neelsg Avatar answered Oct 16 '22 23:10

neelsg