How to work with if/else statements in JavaScript

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hrstissiaopai
    New Member
    • Mar 2013
    • 27

    How to work with if/else statements in JavaScript

    One very important part of almost all computer languages are conditional statements, and specifically if/else statements. Here is an example.
    Code:
    if(16==16){
    window.alert("Yes, 16 does equal 16! Amazing!");
    }
    else {
    window.alert("Wait a second... 16 is not equal to 16?");
    }
    Here is an explanation. This code states that if 16 is equal to 16,
    "Yes, 16 does equal 16! Amazing!" will show up in an alert box. If it does not, "Wait a second... 16 is not equal to 16?" will show up in an alert box. Notice that in the parentheses next to the if the two numbers are compared using two equal signs and not just one:
    Code:
    if(16==16)
    The reason for this is that = is an assignment operator, which is used to assign values to variables, but == is a comparison operator, used to compare two values. Other comparison operators include <= (less than or equal to), >= ( greater than or equal to), =, > and <.
    The code shown above, however, is not really useful. A way of making it useful is shown below:
    Code:
    var age=prompt("What is your age?");
    if(age<6){
    window.alert("You are under 6. You need the parental password.");
    var pass=prompt("Type in the password to continue.");
    if(pass=="parentpassword"){
    window.alert("The password you inserted is correct. Go on!");
    window.location="google.com";
    }
    else{
    window.alert("Your password is wrong");
    }
    }
    else{
    window.alert("You are over 6. You are good to go.");
    window.location="google.com";
    }
    As you can see in the above code, if/else statements are very helpful, and you can also put if/else statements inside other if/else statements (also called nested if/else statements). They form a fundamental part of many computer programs. Try experimenting with them!
  • hrstissiaopai
    New Member
    • Mar 2013
    • 27

    #2
    Can anyone confirm if this code actually works because a few times it didn't, for some reason.

    Comment

    • omerbutt
      Contributor
      • Nov 2006
      • 638

      #3
      yes it does work for me in FF and IE 10 , which browser were you using to test the code.
      regards,
      Omer Aslam

      Comment

      • hrstissiaopai
        New Member
        • Mar 2013
        • 27

        #4
        Thanks. I usually use Chrome or Opera, but I also have IE and FF. I appreciate you taking the time to test it.
        P.S.: Isn't IE 10 Windows 8-only?

        Comment

        Working...