Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If else statement in JavaScript keeps returning last else statement no matter user input

 var age = prompt('How old are you?');
    if ('age' <= 5){
        alert("You are a baby!");
    }
    else if ('age' >= 5 && 'age' < 18){
        alert("You are a child!");
    }
    else if ('age' >= 18 && 'age' < 70){
        alert("You are an adult!");
    }
    else
        alert("You are a senior!");

So I am trying to make it change depending on user input for age. However, no matter the age I enter "You are a senior!" is the only alert that goes off.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You need to remove those inverted commas ‘ ‘ or quotes around age within If condition. By putting 'age', you are using it as a string, but it is a variable age.

  var age = prompt('How old are you?');
    if (age <= 5){
        alert("You are a baby!");
    }
    else if (age >= 5 && age < 18){
        alert("You are a child!");
    }
    else if (age >= 18 && age < 70){
        alert("You are an adult!");
    }
    else
        alert("You are a senior!");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading