Search code examples
javascriptcompareprompt

Prompt user for input then print smallest number


Im trying to accept 2 inputs from a user then compare the 2 to find the smallest number.

Finally print to the console. I feel Im going in the wrong direction.

Any advice?

Below is my code

//prompt variable for user input
let num1 = prompt("Enter 1st number ", "i.e. 7 ");
let num2 = prompt("Enter 2nd number ", "i.e. 4 ");


// for loop returning lowest input

for (let i = 1; i < num1.length; i++){
    if (num1[i] <= num2){
        num2 = num1[i];   
    }
}

console.log(num2);

Solution

  • If there's only 2 inputs and you're trying to console.log the smallest number then you can just use an if statement. No need to iterate through num1.

    let num1 = 5;
    let num2 = 10;
    
    if(num1 > num2){
       console.log(num2);
    }else if (num2 > num1){
       console.log(num1);
    }else{
       console.log(num1 + ' and '+num2+' are equal');
    }