JavaScript Tutorials - If Else Statement Tutorial

Statements carry out some instructions as long as a set condition is true. These few JavaScript statements allow you to do a lot of different things.

Sample Pseudo Code:

If-Else

If-else statements are arguably the most common and useful JavaScript statements. Generally, they come in two forms:

if (condition) 
{
    statement1
}else {
    statement2
 }

There are several different ways to compare variables. The simplest is comparing for equality, which is done using a double equals sign, As you can see we use the if / else statement to test the value of our variable firstname.


<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var firstname="Fergal";
if (firstname=="Fergal") {
	alert("Welcome back " + firstname);
}else{
	alert("Welcome new user " + firstname);
}
</SCRIPT>
</HEAD> 
</HTML>


The result here is Welcome back fergal. We could of tested numerical values also

Example:


var x = 3;
var y = 5;
if(x > y){
alert("x is greater the y");
}else{
alert("x is less than y");
}

When the above code is evaluated an alert box will pop up saying x is less than y.

javascript tutorials