+ 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

28th Feb 2018, 4:55 PM
Abdul Basit
Abdul Basit - avatar
5 Respostas
+ 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.
28th Feb 2018, 5:02 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 2
What if I want to add both strings? Means I want the result 10 not 82. Is there a way?
28th Feb 2018, 5:08 PM
Abdul Basit
Abdul Basit - avatar
+ 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
28th Feb 2018, 5:18 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 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.
1st Mar 2018, 12:02 AM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar
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) );
28th Feb 2018, 5:26 PM
Lewis
Lewis - avatar