0

I've done it to be honest, but I feel like I'm writing extra code. I want a shortcut.

The code is:

let num1 = +prompt("enter a number");
let num2 = +prompt("enter a number");

if(isNaN(num1) || isNaN(num2) || num1 == num2) {
    alert("Error!")
} else{
    let smallnum = 0, bignum = 0;
    if (num1 > num2){
        smallnum = num2;
        bignum= num1;
    } else{
        smallnum = num1;
        bignum = num2;
    }
    i = smallnum + 1;
    while(i < bignum){
        if (i % 2 == 1){
            i++;
            console.log(i);
        } else {
            console.log(i);
        }
        i += 2;
    }
}

Please tell me whether I've written well or not.

2 Answers 2

2
  • You can use max and min to get the lowest and highest number.

  • You can also use the check for even or not even only on the start.

  • If you wrap it in a function, you can end earlier and clean up the if statement

     let num1 = +prompt("Enter a number");
     let num2 = +prompt("Enter another number");
    
     printEvenNumber(num1, num2);
    
     function printEvenNumber(num1, num2) {
         // Exit early
         if (isNaN(num1) || isNaN(num2) || num1 === num2) {
             alert("Error!");
             return false;
         }
         // Use min and max
         let smallnum = Math.min(num1, num2);
         let bignum = Math.max(num1, num2);
    
         // Start from the next even number after smallnum
         let start = smallnum % 2 === 0 ? smallnum + 2 : smallnum + 1;
    
         for (let i = start; i < bignum; i += 2) {
             console.log(i);
         }
     }
    
0
2

If smallnum is even and bignum is the next even number, then the code will print out bignum which is not between the two numbers.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.