+ 3

In Javascript ("11" + 1 = 111) and ("11" - 1 = 10). Why? 😇

JavaScript

7th Apr 2022, 12:20 PM
SAIQA CHANNA
SAIQA CHANNA - avatar
4 Réponses
+ 3
The - operator is only used for number's so it will convert the left hand side and right hand side to numbers and subtract. The + operator is used for string concatenation and addition for numbers. If either the lhs or rhs is a string the other operand gets converted to a string (it will be used as a string concatenation)
9th Apr 2022, 11:50 AM
Joël Egger
Joël Egger - avatar
+ 1
JavaScript is a weakly typed language, meaning that when an operation is called on two types that don't match, the compiler will silently attempt to cast one of the values to another type in order to succeed with the operation. Thus, in your example when using the '+' operator, the compiler puts precedence on casting to strings and concatenating; when you use the '-' operator, the compiler attempts to cast into a number to get a valid result. Hope this gives you some insight ✌️
8th Apr 2022, 6:41 PM
Sam
0
😀😀😀😀 Great !!!.
9th Apr 2022, 6:15 AM
Fabio Pintore
Fabio Pintore - avatar