423,850 Members | 1,661 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

How to work with if/else statements in JavaScript

P: 27
One very important part of almost all computer languages are conditional statements, and specifically if/else statements. Here is an example.
Expand|Select|Wrap|Line Numbers
  1. if(16==16){
  2. window.alert("Yes, 16 does equal 16! Amazing!");
  3. }
  4. else {
  5. window.alert("Wait a second... 16 is not equal to 16?");
  6. }
  7.  
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:
Expand|Select|Wrap|Line Numbers
  1. if(16==16)
  2.  
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:
Expand|Select|Wrap|Line Numbers
  1. var age=prompt("What is your age?");
  2. if(age<6){
  3. window.alert("You are under 6. You need the parental password.");
  4. var pass=prompt("Type in the password to continue.");
  5. if(pass=="parentpassword"){
  6. window.alert("The password you inserted is correct. Go on!");
  7. window.location="google.com";
  8. }
  9. else{
  10. window.alert("Your password is wrong");
  11. }
  12. }
  13. else{
  14. window.alert("You are over 6. You are good to go.");
  15. window.location="google.com";
  16. }
  17.  
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!
Mar 16 '13 #1
Share this Article
Share on Google+
3 Comments


P: 27
Can anyone confirm if this code actually works because a few times it didn't, for some reason.
Apr 17 '13 #2

omerbutt
100+
P: 638
yes it does work for me in FF and IE 10 , which browser were you using to test the code.
regards,
Omer Aslam
Apr 25 '13 #3

P: 27
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?
Apr 25 '13 #4