JavaScript Basics :
IF AND ELSE








Sometimes javascript requires the ability to make distinctions between different possibilities.

For example, you might have a script that checks which browser the user arrives with. If it's MSIE, a page specifically designed for that browser should be loaded, if it's Netscape another page should be loaded.




The general syntax for if statements is:

if (condition) {action1} else {action2};

An example could be:

if (browser=="MSIE") {alert("You are using MSIE")}
else {
alert("You are using Netscape")};


Again it is important to note that if is written as "if".
Using the capital "IF" would cause an error.

Also note that when comparing variables you will need to have two equals signs next to each other (==).

If we wrote browser="MSIE" we would actually store "MSIE" in the variable called browser.

When you write browser=="MSIE" javascript knows that you want it to compare rather than assign a value.

The next section explains the different operators (=, <, > etc.).




More complex if statements can be made by simply entering new if statements in the else part:

if (condition) {action1}
else {if (
condition) {action2} else {action3};};


An example:

if (browser=="MSIE") {alert("You are using MSIE")}
else {if (
browser=="Netscape") {alert("You are using Netscape")}
else {
alert("You are using an unknown browser")};};






AND, OR & NOT

To further enhance your if statements you can use the so-called logical operators.

And is written as && and is used when you want to check if more than one condition is true.

Ex: If the basket contains egg and the basket contains bacon, we can have egg and bacon.

The syntax is: if (condition && condition) {action}

if (hour==12 && minute==0) {alert("it's noon")};






Or is written as || and is used when more than a one condition should result in the check being true. (|| is achieved by using the shift key combined with the \ key)

Ex: If the basket contains milk or the basket contains water, we can have something to drink.

The syntax is: if (condition || condition) {action}

if (hour==11 || hour==10) {alert("it's less than 2 hours till noon")};






Not is written as ! and is used to invert the result.

Ex: If not the basket contains egg or not the basket contains bacon, we cant have egg and bacon.

The syntax is: if (!(condition)) {action}

if (!(hour==11)) {alert("it's more than 1 hour till noon")};


 << PREVIOUS
READ MORE >>  
















DEVELOPER TIP!





     "Better Than Books - As Easy As It Gets!"