Introduction to JavaScript : Conditionals using if

Conditionals using if

You may need to perform certain tasks based on whether a condition is true or false. The 'if', 'if...else', 'if...else if...else' statements allow us to take different paths within a program.

If statement

The 'if' statement evaluates an expression and performs a set of tasks when the expression evaluates to true. For example:

var my_name = "teachsomebody"
var your_name = "teachsomebody"
if (my_name === your_name) {
   console.log("We have the same names!!!")
}

Since the values of the variables my_name and your_name are the same, the 'if' statement will evaluate to true and code within the 'if' block will be executed.

We have the same names!!!

If else statement

The 'if...else' statement provides a means to execute alternative code when a condition is not met. Example:

var my_name = "teachsomebody"
var your_name = "teach"
if (my_name === your_name) {
   console.log("We have the same names!!!")
}
else {
   console.log("We have different names")
}

Since 'teachsomebody' and 'teach' are not the same, the statement in the 'else' block will execute instead of the code in the 'if' block.

We have different names

If else if else

The 'if...else if...else' statements provide multiple paths or decision points within a program as opposed to only two paths as described in the previous section. The example below shows four possible paths:

var my_name = "teachsomebody"

if (my_name === "Teach") {
   console.log("My name is " + my_name)
}
else if (my_name === "teachsome") {
   console.log("My name is " + my_name)
}
else if (my_name === "teachsomebo") {
   console.log("My name is " + my_name)
}
else {
   console.log("All conditions were wrong")
   console.log("My name is " + my_name)
}

The output will be:

All conditions were wrong

My name is teachsomebody

Since all the three comparisons were false.


course logo
Introduction to JavaScript
Number of sections:
10
Content length:
Delivery formats: