One very important part of almost all computer languages are conditional statements, and specifically if/else statements. Here is an example.
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:
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:
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!
Code:
if(16==16){ window.alert("Yes, 16 does equal 16! Amazing!"); } else { window.alert("Wait a second... 16 is not 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 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"; }
Comment