Here is my code :
function jeu(x, y) {
let v1 = x,
v2 = x;
x > y ? v1 = y : v2 = y;
alert(v2 - v1);
}
jeu(2, 10);
There is 2 parameters : x
and y
.
The two first line are putting to v1
the smallest value and to v2
the biggest as you can understand. But when I use some numbers like jeu(2,10)
, the code returns a negative number whereas I am doing "Biggest – Smallest".
Does anybody know why it does that ? (sorry for my bad english)(I can’t put this like code, idk why.
2
Answers
In your case,
"10"
and"2"
are treated as strings, not as numbers.If you want to perform numeric subtraction, you should convert the strings to numbers using
parseInt()
orparseFloat()
like this:Instead of creating two variables
v1
andv2
which are hard to understand, name themmin
andmax
. Assign both of them with conditional logic.May be overkill, but you could use
Math.min
andMath.max
as well:The simpler version is calling
Math.abs
: