And inside if in javascript

And inside if in javascript

Last updated: Jan 2, 2023
Reading time · 4 min

banner

# Specify multiple conditions in an if statement

Use the logical AND (&&) and logical OR (||) operators to specify multiple conditions in an if statement.

When using logical AND (&&), all conditions have to be met for the if block to run.

When using logical OR (||), at least one condition has to be met for the if block to run.

Copied!
// ✅ Using logical OR (||) - at least 1 condition has to be met const num = 5; if (num > 10 || num > 5 || num > 0) // 👇️ if block runs console.log('✅ at least one condition is met'); > else console.log('⛔️ neither condition is met'); >

using logical or to specify multiple conditions

We used the logical OR (||) operator to chain multiple conditions in an if statement.

If none of the conditions return true , the else block will run.

# Using the logical AND (&&) operator — all conditions have to be met

Here’s an example of specifying multiple conditions using the logical AND (&&) operator.

Copied!
// ✅ Using logical AND (&&) - all conditions have to be met const num = 5; if (10 > num && 6 > num) // 👇️ if block runs console.log('✅ all conditions are met'); > else console.log('⛔️ not all conditions are met'); >

using logical and operator to specify multiple conditions in if statement

When using the logical AND (&&) operator in an if statement, all conditions have to be met for the if block to run.

Both conditions in the example return true , so the if block is run.

# Using the logical AND (&&) and logical OR (||) operators in a single if

You can also use the logical AND (&&) and logical OR (||) operators in a single if statement.

Copied!
const num = 5; if ((num > 20 && num > 30) || (10 > num && 15 > num)) // 👇️ if block runs console.log('✅ at least one condition is met'); > else console.log('⛔️ neither condition is met'); >

using logical and and logical or operators in single if

First, the condition to the left (in the parentheses) is evaluated and returns false .

Then the logical OR (||) operator evaluates the condition to the right.

The condition to the right evaluates to true , so the if block is run.

Notice that we used parentheses to group our code and make it more readable.

# Using the every() method to specify multiple conditions

This is a two-step process:

  1. Add the conditions to an array.
  2. Use the Array.every() method to iterate over the array.
  3. Return each condition.
Copied!
const num = 5; const conditions = [num > 1, num > 2, num > 3]; const allConditionsMet = conditions.every(condition => condition); console.log(allConditionsMet); // 👉️ true if (allConditionsMet) // 👇️ this runs console.log('All conditions are met'); > else console.log('Not all conditions are met'); >

We stored the conditions we want to check for in an array.

The function we passed to the Array.every method gets called with each element in the array.

On each iteration, we return the current condition as is.

The every() method returns true if the callback function returns a truthy value on all iterations.

The code sample checks if all of the specified conditions are met.

# Using the some() method to specify multiple conditions

If you need to check if at least one of the specified conditions is met, use the Array.some() method.

  1. Add the conditions to an array.
  2. Use the Array.some() method to iterate over the array.
  3. Return each condition.
Copied!
const num = 5; const conditions = [num > 10, num > 20, num > 3]; const atLeastOneConditionMet = conditions.some(condition => condition); console.log(atLeastOneConditionMet); // 👉️ true if (atLeastOneConditionMet) // 👇️ this runs console.log('At least one condition is met'); > else console.log('None of the conditions are met'); >

The function we passed to the Array.some() method gets called with each condition from the array.

On each iteration, we return the condition as is.

If the callback function returns a truthy value at least once, the some() method returns true and short-circuits.

Otherwise, the some() method iterates over the entire array and returns false .

The code sample checks if at least one of the specified conditions is met.

# Using an if/else if /else statement

You can also use an if/else if/else statement to specify multiple conditions.

Copied!
const num = 5; if (num > 5) console.log('num is greater than 5'); > else if (num > 0) // 👇️ this runs console.log('num is greater than 0'); > else console.log('num is less than or equal to 0'); >

The if statement checks if the variable stores a number greater than 5 .

The condition isn’t met, so the else if condition is evaluated.

The condition is met, so the else if block is run.

The else statement is only run if the conditions in the if and else if statements evaluate to false .

Copied!
const num = 0; if (num > 5) console.log('num is greater than 5'); > else if (num > 0) console.log('num is greater than 0'); > else // 👇️ this runs console.log('num is less than or equal to 0'); >

The num variable stores a value of 0 , so the if and else if statements evaluate to falsy , so the else block is run.

You can also use as many else if statements as necessary.

Copied!
const num = -5; if (num > 5) console.log('num is greater than 5'); > else if (num > 0) console.log('num is greater than 0'); > else if (num > -10) // 👇️ this runs console.log('num is greater than -10'); > else console.log('num is less than or equal to -10'); >

The second else if statement checks if the num variable stores a value greater than -10 .

The condition is met, so its code block runs.

If none of the conditions are met, the else block runs.

You don’t have to specify an else statement if you don’t need it.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Specify Multiple Conditions Inside the if Statement in JavaScript

Specify Multiple Conditions Inside the if Statement in JavaScript

  1. Using Logical Operators to Add Multiply Conditions Inside the if Statement in JavaScript
  2. Using AND and OR Operators in Combination Inside the if Statement in JavaScript

In programming, if we want to execute a code when a particular condition or conditions are satisfied, then in such cases, we make use of something called if statements. Let’s say we have an array of integers, and we want to check whether the number say 20 is present inside the array or not. We do this by adding a condition inside the if statement as follows.

var arr = [5,25,70,62,20,89];  arr.forEach(num =>   if (num == 20)  //do something  > >) 

This is an example where we have only added a single condition inside the if statement. But there are situations while writing production-ready software where we have to pass multiple conditions to the if statements. And based on the result of the condition (true or false), we can execute the appropriate code. Now let us understand how to write an if statement that contains multiple conditions.

Using Logical Operators to Add Multiply Conditions Inside the if Statement in JavaScript

To add various conditions inside the if statement, we make use of logical operators. There are four logical operators in JavaScript, out of which we will use two logical operators AND ( && ) and OR ( || ). These two operators will help us to separate the different conditions inside the if statement. Let’s see how these operators work and how to use them.

The AND ( && ) operator works in this way if you have many conditions, and if any one of the conditions is false , the overall result will be false . For more information, please see the truth table below.

var arr = [5,25,70,62,20,89];  arr.forEach(num =>   if (num == 20 && num%2 == 0)  console.log(num); > >) 

In this example, we have two conditions inside the if statement. The first condition checks whether the current number of the array is 20 or not. If the condition holds, then it will return true and false otherwise. The second condition checks whether the current number of the array is even or not. And if that’s correct, then it will be true and false otherwise.

The OR ( || ) operator works in this way if you have many conditions, and if any one of the conditions is true , the overall result will be true .

The truth table for OR operator:

| A | B | A || B |
| ——- | ——- | :—–: |
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |

var arr = [5,25,70,62,20,89];  arr.forEach(num =>   if (num == 20 || num%2 == 0)  console.log(num);  > >) 

For OR operator, we have taken the same example we have seen for the AND operator, but instead of the && , we have used the || operator. Notice how the output has changed just by changing the operator. This is because the second operator is becoming true three times when the number is 70 , 62 , and 20 .

Using AND and OR Operators in Combination Inside the if Statement in JavaScript

There are some situations where we have to use these operators in combination inside the if statement. The below example illustrates the same.

var arr = [5,25,70,62,20,89];  arr.forEach(num =>   if ( (num != 20 && num%2 == 0) || (num > 50) && (num  100))  console.log(num);  > >) 

Here, we have three conditions inside the if statement. The first condition is a combination of two conditions in itself. In order for the first condition to be true the inner two conditions num != 20 and num%2 == 0 must also be true since there is an && operator. Then we have the second condition to check whether the number is greater than 50 or not. And the third condition is checking whether the number is less than 100 or not.

Notice that there is a || operator between the first and second condition and a && operator between the second and third. According to the precedence of the operators, the && operator has higher precedence than the || operator. Therefore, the second and the third conditions will be evaluated first, and then the result of this will be evaluated with the first condition. To learn more about operator precedence, you can visit this MDN docs.

Apart from just using a single if statement, we can also make use of something called an if and else if statement. This allows us to add multiple if statements, each with different conditions, and each of these code blocks can execute different code. The code snippet below shows this.

var arr = [5,25,70,62,20,89];  arr.forEach(num =>   if ((num > 50) && (num  100))  console.log("The number is in the range of 20 to 100.");  >  else if(num != 20 && num%2 == 0)  console.log("The number 20 is divisible by 2.")  >  else if((num  50) || (num == 5))  console.log("The number is less than 50.")  > >) 
The number is less than 50. The number is less than 50. The number is in the range of 20 to 100. The number is in the range of 20 to 100. The number is less than 50. The number is in the range of 20 to 100. 

Here, we have added if and various else if statements, each containing multiple conditions. Now depending upon the number present inside the array, any one of the three conditions will be satisfied, and the code inside that particular code block will be executed.

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.

Источник

Читайте также:  Что такое css информатика
Оцените статью