Home > front end >  made a function to find the max between 3 numbers but returns " 0"
made a function to find the max between 3 numbers but returns " 0"

Time:03-09

so this is what i did, if anyone has some free time maybe you could see what i did wrong? i cant seem to figure it out and i'm very curious :c

let mayor = 0;

function max(a, b, c) {
  for (let i = 0; i <= max.length; i  ) {
    if (max[i] > mayor) {
      mayor = max[i];
    }
    return mayor;
  }
}

let mayorFin = max(5, 2, 6);

console.log(mayorFin); // 6 // 6

it returns the 0 so it never changes mayor to the max in between parenthesis.

I'm in the process of learning and i believe there's no such thing as a dumb question, any help is much appreciated form the bottom of my heart cause' your time is valuable, thanks!

CodePudding user response:

max is not an array. create an array inside function and use it. like this:

let mayor = 0;

function max(a, b, c) {
  let arr = [a, b, c]

  for (let i = 0; i <= arr.length; i  ) {

    if (arr[i] > mayor) {

      mayor = arr[i];

    }
  }
  return mayor;

}

let mayorFin = max(5, 2, 6);

console.log(mayorFin); // 6 // 6

CodePudding user response:

You may use "..." operator like this. It allow you insert any amount of arguments into your function.

function max(...args) {
  let mayor = 0;

  for (let arg of args) {
    if (arg > mayor) mayor = arg;
  }
  return mayor;
}

let mayorFin = max(5, 2, 6);

console.log(mayorFin); // 6 // 6

  • Related