HI WELCOME TO KANSIRIS

Why the result of (alert ('5' + 5 + 5);) in Jquery the result will be 555 not 510?

Leave a Comment
What you are trying to do here is adding a string with two numbers. In some languages this would result in an error, but JavaScript is a friendly language and likes to think with you.
To know how JS solves this problem you need to know:
  1. What does JS do when you try to add a string with a number.
  2. In what order will JS solve this equation.
1. When you try to add two values of different types, JS will convert one of them to make them the same type. This is called coercion. When these types are number and string, it will change the number type into string type.
2. To know in which order operators are resolved, you can check the table of JavaScript Operator Precedence. Because in this case both operators are the same, we have to look at the associativity.  Associativity determines the order in which operators of the same precedence are processed. According to the table the equation will be resolved from left to rigth.
So it will be resolved as follows:
step 1: '5' + 5  => '5' + '5' => '55'
step 2: '55' + 5 => '55' + '5' => '555'
If you want the result to be 510, you'll have to change your equation as follows:
'5' + (5 + 5) Because grouping (the parentheses) has the highest precedence in the table, this will be resolved as follows:
step 1: (5 + 5) => 10 (both are numbers, so no coercion)
step 2: '5' + 10 => '5' + '10' => '510'
Please also note that because of the associativity, '5' + 5 + 5 is not the same as 5 + 5 + '5'. the first will resolve into the string 555 and the second will resolve into the string 105. Can you see why?
As you can see, coercion can give unexpected results, try to avoid it by only adding primitives of the same type.
As per my knowledge , when we  do '5'+5 , plus operator works like con cat operator  so it will work like
for example ,
'5'+5 = '55'
'55'+5='555'
5+5 = 10
5+'5'+5 ='555'
5+5+5= 15
general example
String + number = String
number + number = number


Let me know if i  am wrong

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.