I am writing my own function which returns lower argument between two arguments.
My first solution was:
function min(a, b) {
if (a < b)
return a;
else
return b;
}
console.log(min(0, 10));
// → 0
But I wanted to simplify it and wrote another one function:
function min(a, b) {
return a ? a < b : b;
}
console.log(min(0, 10));
// → true
Why my second function returns boolean value instead of number? Can I change this behavior?
It should be
function min(a, b) {
return a < b ? a : b;
}
console.log(min(0, 10));
Your ternary operater is a little funky.
It should be boolean ? returnValueForTrue : returnValueForFalse;
boolean ? returnValueForTrue : returnValueForFalse;
So yours is doing a ? boolean : b
a ? boolean : b
and I'm not sure what that actually turns into. a ? boolean
a ? boolean
would turn into a boolean.
So yours should be
return a < b ? a : b;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.