Code highlights logo


Conditional Statements

If...Else Statements

The if...else statement provides a way to execute one block of code if a condition is true and another block of code if the condition is false. It allows for branching within our code, making it more dynamic and flexible.

1if (condition) {
2 // code to be executed if the condition is true
3} else {
4 // code to be executed if the condition is false

Examples and Syntax

Let's take a look at some examples to better understand the syntax and usage of if...else statements.

1let num = -5;
3if (num >= 0) {
4 console.log("The number is positive or zero.");
5} else {
6 console.log("The number is negative.");

Nesting If...Else Statements

We can also nest if...else statements within each other to create more complex conditions and decision-making processes.

1let num = 10;
3if (num > 0) {
4 console.log("The number is positive.");
5} else {
6 if (num < 0) {
7 console.log("The number is negative.");
8 } else {
9 console.log("The number is zero.");
10 }



Declare a variable called grade and assign it a value of 85.


Declare a variable called result, that we will change later on.


Write an if...else statement to check if the grade is greater than or equal (>=) to 80. If the condition is true, assign the string "Pass" to our variable result.


If the grade is less than 80, assign the string "Fail" to the result variable.


Print the value of the result variable to the console.

Sign up to start coding

Already have an account?

Sign In

Course content