Code Highlights logo

Learn

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
5}

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;
2
3if (num >= 0) {
4 console.log("The number is positive or zero.");
5} else {
6 console.log("The number is negative.");
7}

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;
2
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 }
11}

Instructions

1.

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

2.

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

3.

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.

4.

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

5.

Print the value of the result variable to the console.

Sign up to start coding

Already have an account?

Sign In

Course content