+ 2

Why is addition the only thing weird?

How does 5 - '5' = 0, 5*'5' = 25, 5/'5' = 1, but 5+'5' is 55?

8th Mar 2023, 10:50 PM
Steel
Steel - avatar
2 ответов
+ 7
It is because of string concatenation. In javascript if one of data is string, and another is number it will change type to number and do calculation. But if you use "+" what is used in string concatenation it will change it to string and place this 2 strings together so we get 55 not 10. When you work with data from user it will always be string type, you would need to convert it to number. Here is article about string concatenation: https://www.scaler.com/topics/string-concatenation-javascript/ And about, how to convert string to number, this cover many ways, but first 2 are mostly used https://www.freecodecamp.org/news/how-to-convert-a-string-to-a-number-in-javascript/amp/
8th Mar 2023, 11:49 PM
PanicS
PanicS - avatar
+ 2
In Javascript remember the following rules: 1. Number + string =string , string+ number = number //concat both of them // if there is a string after a number the + sign always consider as concatenate 2. Number - string = number , string - number = number // subtracting-> both value are considered number 3. Number * string = number, string*number = number // multiplication -> both value are considered number 4. Number / string = number , string/number = number // division-> both value are considered number ______________________________________________ note: Javascript always translate code for left to right by considering priority rules EX: 4*"2"+4+"3" +6 we break down it : 4*"2"=8 // rule number 3 above 8+4= 12 12+"3"= 123 // rule number one above 123+6=1236 // rule number one - second structure I hope it becomes helpful for you .
10th Mar 2023, 12:50 AM
Yasin Rahnaward
Yasin Rahnaward - avatar