The if/else statement block structure

An if/else statement begins with the JavaScript keyword if followed by a comparison in parentheses.


if (NumberOne >= 100)

The comparison between parentheses must return true or false. If it returns true then the browser can go on to the next line. If it returns false then the browser begins looking for the else keyword or the first line of code after the block following the if line is completed.

If the comparison returns true then the block of statements after the if line (which are placed within curly brackets) will be executed.


if (NumberOne >= 100) {
     window.alert("You have the right number to begin with!");
}

If NumberOne is greater or equal to 100 then the browser will display an alert that says You have the right number to begin with!.

If the comparison returns false then you can use else keyword to tell the browser to execute the code that follows it.


if (NumberOne >= 100) {
     window.alert("You have the right number to begin with!");
}
else {
     window.alert("Wrong number!");
}

In order to know if comparison returns true or false you need to declare the NumberOne variable and assign it a value before the comparison takes place.


var NumberOne = 105;
if (NumberOne >= 100) {
     window.alert("You have the right number to begin with!");
}
else {
     window.alert("Wrong number!");
}

The variable NumberOne is assigned a value of 105 which is greater than 100 which means the comparison returns true. Since the comparison returns true the first line of code after the if statement will be executed. The browser will display an alert that says You have the right number to begin with!.

If you assign a value to the variable NumberOne that is less than 100 then the comparison returns false and the code after else keyword will be executed, therefore the browser will display an alert that says Wrong number!.


var NumberOne = 90;
if (NumberOne >= 100) {
     window.alert("You have the right number to begin with!");
}
else {
     window.alert("Wrong number!");
}

Leave a Reply