if statement js

If Statement in JS

If statement in JavaScript is a conditional statement used to execute a block of code if a particular condition is true. The syntax for writing an if statement is:

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

The condition in the if statement is an expression that can be evaluated as either true or false. If the condition is true, then the code inside the curly braces will be executed, otherwise, it will be skipped.

Example:

Let's take an example to understand how if statement works in JavaScript. Suppose we want to check whether a number is even or odd:

let num = 4;

if (num % 2 === 0) {
  console.log(num + " is even");
} else {
  console.log(num + " is odd");
}

The above code will output "4 is even" because the condition in the if statement is true as the remainder of num divided by 2 is 0. If the condition was false, then the code inside the else block would have been executed.

Multiple Conditions:

We can also use multiple conditions in an if statement using logical operators like AND (&&) and OR (||). For example:

let num1 = 10;
let num2 = 5;

if (num1 > num2 && num1 % 2 === 0) {
  console.log(num1 + " is greater than " + num2 + " and even");
} else if (num1 > num2 && num1 % 2 !== 0) {
  console.log(num1 + " is greater than " + num2 + " and odd");
} else {
  console.log(num2 + " is greater than " + num1);
}

The above code will output "10 is greater than 5 and even" because both conditions in the if statement are true. If the first condition was false, it would check the second condition and so on.

Nested If Statements:

We can also nest if statements inside another if statement to create more complex conditions. For example:

let num = 15;

if (num % 2 === 0) {
  if (num % 3 === 0) {
    console.log(num + " is divisible by both 2 and 3");
  } else {
    console.log(num + " is only divisible by 2");
  }
} else {
  console.log(num + " is not divisible by 2");
}

The above code will output "15 is only divisible by 3" because the first condition is false and it executes the else block. However, if the first condition was true, it would check the second condition inside the nested if statement.

Conclusion:

In conclusion, if statement in JavaScript is a powerful tool for creating conditional statements that can execute a block of code based on a particular condition. We can use logical operators to create complex conditions and nest if statements inside another if statement to create even more complex conditions.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe