Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript find max number from 3 inputs

Tags:

javascript

max

I've just began Javascript in college. One task is to define and call a function to find the maximum number from 3 numbers entered by the user. I know there is a max() function but we were told to do it manually using if and else if.

I'm going wrong somewhere as you can see. It's just telling me the max is 0 everytime.

function maxNum(num1, num2, num3){
        var max = 0;
        if(num1 > num2){
            if(num1 > num3){
                num1 = max;
            }
            else{
                num3 = max;
            }
        }
        else{
            if(num2 > num3){
                num2 = max;
            }
        }
    return max;
    }

    for(i=0;i<3;i++){
        parseInt(prompt("Enter a number"));
    }
    document.write(maxNum());
like image 792
Pizzaman Avatar asked Feb 28 '26 10:02

Pizzaman


2 Answers

Or you can use ES6 syntax, to compute largest of three numbers in easier way,

const largest = a => F = b => G = c => ((a > b && a > c) ? a : (b > a && b > c) ? b : c)

console.time()
console.log(largest(53)(30907)(23333))
console.timeEnd()
like image 120
Suresh KUMAR Mukhiya Avatar answered Mar 03 '26 01:03

Suresh KUMAR Mukhiya


One problem you have is that you do not save the number the user inputs. You prompt them, parse it as an int and then nothing. You have to pass the 3 numbers into maxNum()

Here is a working example that uses proper left hand assignment and saves the number. Also it is a good idea to use >= instead of > because the user can enter 2 of the same number

function maxNum(num1, num2, num3){
        var max = 0;
        if((num1 >= num2) && (num1 >= num3)){
            max = num1;
        }
        else if((num2 >= num1) && (num2 >= num3)){
            max = num2;
        }
        else{
            max = num3;
        }
    return max;
    }

    var arr = []; 
    for(i=0;i<3;i++){
        arr[i] = parseInt(prompt("Enter a number"));
    }


    document.write(maxNum.apply(this, arr));
like image 43
Bijan Avatar answered Mar 03 '26 01:03

Bijan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!