Reputation: 171
Hi I'm new to this site and programming so I'm sorry if this question is dumb. I'll get to the point.
If (a == 1 && b == 2)
{
executeFunction
}
If (a == 2 && b == 3)
{
executeSameFunctionAsAbove
}
How would I combine the two if statements? Both will execute the same function.
Upvotes: 2
Views: 736
Reputation: 2725
you'r looking for JavaScript If...Else Statements
Conditional Statements Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
- Use if to specify a block of code to be executed, if a specified condition is true
- Use else to specify a block of code to be executed, if the same condition is false
- Use else if to specify a new condition to test, if the first condition is false
- Use switch to specify many alternative blocks of code to be executed
and JavaScript Logical Operators :
&& and (x < 10 && y > 1) is true
|| or (x == 5 || y == 5) is false
! not !(x == y) is true
So using conditional statements you function would be like
if ((a == 1 || a == 2)&& (b == 2 || b == 3))
{
executeFunction
}
Upvotes: 1
Reputation: 340
if ((a == 1 && b == 2) || (a == 2 && b == 3)){
executeFunction
}
Simply use parenthesis to group conditions, and check if one or more statements are true with the OR operator
(||
).
According to this wikipedia article the AND operator
is executed before OR operator
, so you can do the following without any difference:
if (a == 1 && b == 2 || a == 2 && b == 3){
executeFunction
}
Upvotes: 1
Reputation: 157334
It can be,
if ((a == 1 && b == 2) || (a == 2 && b == 3)) {
//your function goes here
}
Here, we check if either of the two condition matches separating them with ||
which is nothing but an OR operator.
Just couple of suggestions here,
type
sensitive, make sure you use ===
which will check for the data type as well while comparing and not just the valuevar
keywords for each on of them else they'll be global.Upvotes: 2
Reputation: 2285
combine both conditions with or
If (a == 1 && b == 2 || a == 1 && b == 2)
{
executeFunction;
}
Please note than the &&
operation will be executed before the ||
operation. But for any general conditions you may use parentheses for every one like this.
If ((some conditions) || (some other conditions) || ...)
Or for your case
If ((a == 1 && b == 2) || (a == 1 && b == 2))
do_someting();
Upvotes: 0