1

I am learning JavaScript. I was playing around and wrote a function to find the largest integer. It works just fine, but I was wondering how I can DRY it up.

function largerInt(int1, int2, int3, int4) {
  if (int1 > (int2 && int3 && int4)) {
    console.log(int1);
  } else if (int2 > (int1 && int3 && int4)) {
      console.log(int2);
    } else if (int3 >(int1 && int2 && int4)) {
      console.log(int3);
    } else if (int4 >(int1 && int2 && int3)) {
      console.log(int4);
    }
  

}
  • You mean the largest number between int1, 2, 3, 4? – Sajeeb Ahamed Oct 29 '20 at 06:01
  • 2
    Sidenote, `(int1 > (int2 && int3 && int4)` doesn't do what you think it does. [Is && statement() the same as if() statement()?](https://stackoverflow.com/q/12664230) | [What is “x && foo()”?](https://stackoverflow.com/q/6970346) | [Javascript AND operator within assignment](https://stackoverflow.com/q/3163407) – VLAZ Oct 29 '20 at 06:01
  • "*It works just fine"* so, have you tried `largestInt(2, 3, 1, 0)`? – VLAZ Oct 29 '20 at 06:05

2 Answers2

0

You are using too many if and else and your function works only with exactly 4 parameters. It's much better to make it work with any number of parameters and be more straight forward:

function largerInt(...nums) {
  if (nums.length === 1) {
    return nums[0];
  }
  let largestNum = nums[0];
  for (let i = 1; i < nums.length; i++) {
    if (largestNum > nums[i]) {
      largestNum = nums[i];
    }
  }

  return largestNum;
}

Anatoly
  • 20,799
  • 3
  • 28
  • 42
-1

If you need the largest number then try this-

const largeInt = (...nums) => Math.max(...nums);
console.log(largeInt(3, 4, 2, 9));
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30
  • 1
    If they're struggling with conditions then it's very likely introducing arrow functions and spread syntax isn't going to help them understand why *their* approach isn't working. – Andrew Li Oct 29 '20 at 06:04
  • But he is asking about DRY code, and he may learn from it. Don't worry. @AndrewLi – Sajeeb Ahamed Oct 29 '20 at 06:09
  • @SajeebAhamed It works perfectly, thank you for your help. And thank you all for helping as well. – HammadKhalid Oct 29 '20 at 06:11
  • @HammadKhalid please accept the answer if it helps you and don't forget to upvote so that other can get help. – Sajeeb Ahamed Oct 29 '20 at 06:18