0

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?

5
  • a ? a < b : b what does this expression mean? Commented Feb 7, 2017 at 23:09
  • Can I change this behavior? - what you need to change is your understanding of how condition ? whentruthy : whenfalsey works :p Commented Feb 7, 2017 at 23:10
  • If a is 0 then it's falsey so a? a < b : b should return b (i.e. 10), not true. Commented Feb 7, 2017 at 23:16
  • @zerkms exactly right. I didn't pay attention. Thanks Commented Feb 7, 2017 at 23:18
  • @JaromandaX thanks. Commented Feb 7, 2017 at 23:18

2 Answers 2

2

It should be

function min(a, b) {
   return a < b ? a : b;
}
console.log(min(0, 10));
Sign up to request clarification or add additional context in comments.

Comments

1

Your ternary operater is a little funky.

It should be boolean ? returnValueForTrue : returnValueForFalse;

So yours is doing a ? boolean : b and I'm not sure what that actually turns into. a ? boolean would turn into a boolean.

So yours should be

return a < b ? a : b;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.