+ 2
Confuse in Quiz JS Question
In this question x and y both are string. In case of addition it alerts 28 means they are being treated as string but in case of negation, it alerts 6. Why it's not behaving as string while we subtract both strings? var x = "8"; var y = "2"; alert(x+y); //28 var x = "8"; var y = "2"; alert(x-y); //6
5 odpowiedzi
+ 2
In the first example, the + sign is concatenating the string. It's outputting 82 because you're simply appending the value of 'y' onto the end of 'x.'
In the second example, the - sign is causing it to do actual math calculations, which is subtracting 2 from 8, which is 6.
+ 2
What if I want to add both strings? Means I want the result 10 not 82. Is there a way?
+ 2
Yes, when you declare your variables, don't put the numbers in quotes. The "" quotes is what is declaring it as a string variable instead of an int variable.
EXAMPLE::::
var x = 8;
var y = 2;
alert(x+y);
// Output: 10
+ 2
You can also add a + operator at the beginning of each variable to convert them into numbers.
var x = "8";
var y = "2";
alert(+x + +y);
alerts 10 instead of 82.
0
Assuming you need the two variables to be stored as strings you can use the 'parseInt' function. The first argument is the string to translate into an integer, the second is the base for the numeric system which is optional and defaults to 10 or decimal.
For example that would be:
alert( parseInt(x) + parseInt(y) );