HTML / JavaScript Reference

Conditional Statements

Overview

Most programs use conditional statements to test equality. It is one of the fundamental concepts of programming. It's based on boolean logic, where something is either true or false, on or off, 1 or 0. Here is how a conditional statement would look if expressed in a normal sentence: If it is the morning, then say "Good Morning." See example 2 below for the code equilvalent of that sentence.

Basic Rules

JavaScript uses the if statement to test if a condition is true. If it is true, the statements within the curly braces { } are performed. If it is not true, you can set up alternative tests, using the else if statement. The else if conditions will only be tested if the previous if statement evaluates to false.

The collection of statements enclosed in the curly braces is called a block. The curly braces aren't needed if there is only one line to perform, but you can always include them. Regarding tabbing and spacing, the placement of the curly braces is a matter of style and does not affect the logic.

The equality test is comprised of two equal signs ==. The if statement can also test inequality !=, and "greater/less than" tests >, >=, <, <=. These are all called relational operators. You can combine conditions by using logical operators, && and ||. The first is the "and" operator and the second is the "or" operator.

Basic Rules - example 1 source

var numOne = 1;
var numTwo = 2;
var skyIsBlue = true;

// The following if statement has two conditions
// First, is if the variable numOne equals the variable numTwo
// Second, is if the variable skyIsBlue evaluates to true
if ((numOne == numTwo) && (skyIsBlue))
{
	// The first condition evaluates to false
	//  and the second one is true.
	// They both have to be true, so the code
	//  between these curly braces doesn't get executed.
	// Luckily, there is no code here.
}

Basic Rules - example 2 source

var timeOfDay = new Date();
if (timeOfDay.getHours() < 12)
{
	alert("Good Morning");
}

About this page: