I hope my logic isn’t flawed but I’m reading the Definitive Guide to JavaScript and I don’t understand how this custom abs function works…
function abs(x) {
if (x >= 0) {
return x;
} else {
return -x;
}
}
I recrafted it using a ternary operator in an attempt to understand it…
var res = (x >= 0) ? x : -x;
return res;
… but I still don’t get how it works.
Say I use -10 as x, how does it return +10? How does the sign reverse?
1 Answer