Search code examples
htmlif-statementjscript

How do i fix my else if in jscript? It's not working


i have a super simple jscript program ( in html file). if and else are working, but else if is never working...

var num1 = prompt("Enter first number");
var num2 = prompt("Enter second number");
function result(){
if(num1 == 10 || num2 == 10){
    alert("one of entered numbers is 10, great!")
    return true
}else if((num1+num2) == 10){
    alert("The sum of 2 numbers is 10, great!")
    return true
}else{
    alert("None of numbers, or the sum is 10")
    return false
}
}
alert("Result is: ", result())

So, if one of the numbers is 10 it shows first if, but if it's 5 and 5, or 6 and 4 - it always shows else, i don't understand why else if is always ignored... And how can i alert a result (true/false)? it's always says "Result is: "


Solution

  • I think your prompts are saving the input as strings, here I converted them to integers and it seems to work. https://jsfiddle.net/fk0tr196/

    var num1 = prompt("Enter first number");
    var num2 = prompt("Enter second number");
    num1 = parseInt(num1,10);
    num2 = parseInt(num2,10);
    function result(){
    if(num1 == 10 || num2 == 10){
        alert("one of entered numbers is 10, great!")
        console.log(num1);
        return true
    }else if((num1+num2)== 10){
            console.log(num1);
        alert("The sum of 2 numbers is 10, great!")
        return true
    }else{
        alert("None of numbers, or the sum is 10")
        return false
        console.log(num1);
    }
    }
    alert("Result is: ", result())