Billy Milligan
Billy Milligan

Reputation: 79

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: "

Upvotes: 0

Views: 111

Answers (2)

Victor Oliveira
Victor Oliveira

Reputation: 393

Take a look at type coercion, strict equality and the prompt function is js. The prompt function receives two optional arguments and returns a string (bare with me).

When your result function is called with, let us say, num1 = 5 and num2 = 5, you actually have:

num1 = "5"
num2 = "5"

See the difference? If you don't believe me, just console.log(typeof num1) or num2 and check for yourself!

Now, when you use double equals, you allow type coercion to try to equality, or in another words, you accept that 5 equals "5". This sometimes is helpful but generally you'll want to avoid it and use ===, which only evaluates true if VALUE and TYPE are the same.

In summary,

5 == "5" // true
5 === "5" // false

So, when one of your values is "10", the if statement is true and works. Any other case will fall into else, because when you + two strings you are actually concatenating them. As it is, entering 5 on both prompts will result in "55" in the else if statement, thus leading to false.

There are some ways to convert a string to a number: 1- Number(variable) 2- parseInt(variable) 3- +variable

There are some differences with each but at this stage, you shouldn't be concerned

Upvotes: 1

Ale Plo
Ale Plo

Reputation: 819

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())

Upvotes: 2

Related Questions