DEV Community

Discussion on: '1' - '1' / 2 = ? , Can you find the answer ?

Collapse
 
sthuber90 profile image
Stephan

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:

'1'+'1'*2
// '1' * 2 = 2 <- parses '1' string to number multiplies by two and returns number
// '1' + 2 = '12' <- one element is string therefore the parts get concatenated
// output 12 

'1'+'1'/2
// '1' / 2 = 0.5 <- parses '1' string to number divides by two and returns number
// '1' + 0.5 = '10.5' <- one element is string therefore the parts get concatenated
// output 10.5

// the - operator is not meant for strings. JS tries to parse the parts to numbers.
'1'-'1' 
// parsed to numbers 1-1 = 0
// output 0

'1'-'1'/2
// '1' / 2 = 1 / 2 = 0.5
// '1' - 0.5 = 1 - 0.5 = 0.5
// output 0.5
Enter fullscreen mode Exit fullscreen mode

You can see that the parts in a subtraction, multiplication, division get parsed to a number if you try the following:

true + true = 2
true - false = 0
false - false = 0
false + false = 0
false - true = -1

// and the interesting part
'a' + 'b' = 'ab'
'a' - 'b' = NaN
'a' * 'b' = NaN
'a' / 'b' = NaN
Enter fullscreen mode Exit fullscreen mode