DEV Community

Heru Hartanto
Heru Hartanto

Posted on

3

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

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 ? 

Enter fullscreen mode Exit fullscreen mode

Top comments (2)

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
Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited

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:

function add(a,b) {
   return +a + +b
}
Enter fullscreen mode Exit fullscreen mode

The +a is bound to convert a to be a number (if possible) etc.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up