Code Highlights logo

Learn

Conditional Statements

If Statement

In programming, it is often required to execute different blocks of code depending on certain conditions. The if statement is a fundamental conditional statement that allows you to control the flow of your program based on these conditions. In this lecture, we will explore the if statement in detail and learn how to use it effectively.

Syntax

The if statement follows a specific syntax:

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

The if statement evaluates the specified condition inside the parentheses. If the condition is true, the code block enclosed within the curly braces will be executed. However, if the condition is false, the code block will be skipped, and the program will move on to the next block of code after the if statement.

Example

Let's consider a simple example to understand how the if statement works:

1let x = 10;
2
3if (x > 5) {
4 console.log("x is greater than 5");
5}

In this example, we have declared a variable x and assigned it a value of 10. The if statement checks if the value of x is greater than 5. Since this condition is true, the code block inside the if statement will be executed, and the message "x is greater than 5" will be printed to the console.


Instructions

1.

Declare an if statement that checks if x is greater than y.

2.

Inside the if statement, console.log the message:

1"x is greater than y"

Sign up to start coding

Already have an account?

Sign In

Course content