I just found out some π funny things about javascript, If someone able to explain I really appreciate
'A'+'A'
// output 'AA'
'1'+'1'
// output '11'
// Okay that make sense but ...
'1'+'1'*2
// output 12
'1'+'1'/2
// output 10.5
// It's start getting weird then ....
'1'-'1'
// output 0
'1'-'1'/2
// output 0.5
// It's correct , but why ?
Top comments (2)
Executing
+
on two string concatenates the strings. This explains "AA" and "11".Now
-
,/
and*
are seen as math operations. Given that a multiplictation or division is done before addition and subtraction the other parts can be explained like this:You can see that the parts in a subtraction, multiplication, division get parsed to a number if you try the following:
If there is a numerical operation then the string is converted into a number. The + is a string concatenation operator and a numerical operator, string wins in this case. So "1" concatenate the result of 1*2 = 2 becomes "12" as a string.
Note that
+
on its own is always a numerical operator which is why you might see this:The
+a
is bound to converta
to be a number (if possible) etc.