+ 1
JavaScript challenge question
Can you kindly explain each step of this one?? What is the output of this code? let a = '2'; let b = 5; console.log((b+a) + "" + (b-a));
10 Respostas
+ 6
ODLNT Oh i overlooked haha
EO4Wellness For the - operator, as A͢J has listed, it type coerced the string to number, and perform arithmetic subtraction.
Note that when JavaScript fails to convert string to number, for example, 'abc' - 'abc', there will be no error, the result will be NaN (not a number)
https://code.sololearn.com/cuiVNiJsBY8J/?ref=app
+ 5
EO4Wellness
In JavaScript + is used as String concatination as well as addition of two numbers.
Since there 2 is string and 5 is number so here should be 52
But this behaviour doesn't apply on Subtraction, multiplication, division and modulus operator so
5 - '2' = 3
5 * '2' = 10
5 / '2' = 2.5
5 % 2 = 1
+ 4
Okay so then if I understand both of you correctly: the correct answer is 523 because of concatenation.
52 because of (a+b)
the '''' part adds in effect nothing new because it is an empty string
3 because of the b-a part
??? Is that the correct way of looking at it then???
Thank you both for helping ...
+ 3
brackets are evaluated first.
So
(b+a) is 5 + 2,
numerical addition,
results 7
(b-a) is 5 - 2,
numerical subtraction,
results 3
Now the operation becomes
7 + "" + 3
Note that "" is empty string,
and so the + operator performs string concatenation instead.
Type Coercion occurs!
7 (Number) is converted to "7" (string)
3 (Number) is converted to "3" (string)
So
"7" + "" + "3"
So result is
73
Type Coercion is special in JavaScript, tricky to beginner very often.
+ 3
Gordon Yes. That's what I'm asking about. How does 5-'2' work?
+ 2
This is very tricky! Thank you for taking the time to help. | After completing this challenge, I went back to check the correct answer, because I didn't understand it in relation to the 2 being a string. The answer was given as 523?
+ 2
Thank you for your reply. SoloLearn gives the post-challenge correct answer for this question as 523. Panache Sigauke and Chinedu Gabriel
+ 1
Exactly~ EO4Wellness
0
The result is 73
Coz
5+2 then 5-2
7 then 3
So
73
Not correct bcoz the 2 is a string not an integer, so i got no idea
0
let a = '2'; // string
let b = 5; // number
// ((5 + 2) + "" + (5 +2))
console.log((b+a) + "" + (b-a));
// solution 5252
// Remember that the addition operator ("+") is used for concatination and when adding a string with a number it only joins (concertinate's) the given values without actually adding it, except if both values or data types are numbers but if you use multiplication operator (*) javascript converts the datatype of a “number sting” to a number before carrying any mathematical computation for example console.log("2" * 3);
// **but note if its an actual string multpling a number javascript will return NaN as the result for example console.log("car" * 2);