JavaScript If Statements

JavaScript is a powerful programming language that allows developers to create dynamic and interactive web pages. One of the fundamental building blocks of JavaScript is the “if” statement. The “if” statement is used to execute a block of code if a certain condition is true.

The syntax of the “if” statement in JavaScript is as follows:

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

The condition within the parentheses can be any expression that evaluates to either true or false. If the condition is true, the code within the curly braces will be executed. If the condition is false, the code block will be skipped, and the program will move on to the next statement.

Let’s look at a few examples to understand how the “if” statement works:

Example 1: Checking if a Number is Positive or Negative

let number = 5;

if (number > 0) {
    console.log("The number is positive.");
} else {
    console.log("The number is negative.");
}

In this example, we declare a variable called “number” and assign it a value of 5. The “if” statement checks if the number is greater than 0. Since 5 is indeed greater than 0, the code inside the first block will be executed, and the message “The number is positive.” will be printed to the console.

Example 2: Checking if a User is Logged In

let isLoggedIn = true;

if (isLoggedIn) {
    console.log("Welcome back!");
} else {
    console.log("Please log in to continue.");
}

In this example, we have a boolean variable called “isLoggedIn” that indicates whether a user is logged in or not. The “if” statement checks if the value of “isLoggedIn” is true. If it is, the message “Welcome back!” will be printed. Otherwise, the message “Please log in to continue.” will be displayed.

Example 3: Determining the Grade of a Student

let score = 85;
let grade;

if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 70) {
    grade = "C";
} else if (score >= 60) {
    grade = "D";
} else {
    grade = "F";
}

console.log("Your grade is: " + grade);

In this example, we have a variable called “score” that represents the score of a student in a test. Based on the score, the “if” statement checks multiple conditions using the “else if” syntax. Depending on the value of “score,” a corresponding grade is assigned to the variable “grade.” Finally, the grade is printed to the console.

The “if” statement in JavaScript is a fundamental control structure that allows developers to make decisions based on certain conditions. It is an essential tool for creating dynamic and interactive web pages. By using “if” statements, developers can control the flow of their programs and make them more responsive to user input.

Scroll to Top