JavaScript JavaScript Basics Creating Reusable Code with Functions Create a max() Function

Mathew Yangang
Mathew Yangang
1,427 Points

not sure what i'm doing wrong here

Not sure what i'm doing wrong here

script.js
a=1;
b=2;

function max(a,b){
if(b>a);
  return(2);
}

2 Answers

Paul Scanlon
PRO
Paul Scanlon
Pro Student 20,394 Points

Hey

Almost

var a = 1;
var b = 2;
function max(a, b) {
  if (a > b) {
    return a;
  } else {
    return b
  }
}

You return the variable a or b not the value of them

Hope this helps

Happy coding

Paul

Christian Ali Nazha
PRO
Christian Ali Nazha
Pro Student 1,786 Points

3 mistakes:

  • wrong function syntax
  • your logic works only if a number is bigger than the other, not the other way round
  • always returning the same number instead of the input

Answer:

function max (a,b){ if(a>b){ return a; }else{ return b; } }

This function:

  • Takes two numbers, the first input will be assigned to a while the second is assigned to b
  • A condition checks if a>b, if so, a is returned
  • An else catches the if, and will return b

Although this passes the requirements of your exercise, this has a glitch of always returning 'a' if 'a' and 'b' are equal.