Javascript if with or conditions

Javascript If Condition with multiple OR and AND

please have a look on my if condition. I am just refreshing my javascript and I am wondering, how I could check, if the inserted variables, are the ones I want to be used. Obviously the «game» should only take rock, paper or scissors. Now the if condition says, if (choice 1 and choice 2 equal rock or scissors or paper) < do this; >else But apparently it is not working the way I want.

var choice1 = prompt("Player 1: Rock, scissors or paper?"); var choice2 = prompt("Player 2: Rock, scissors or paper?"); compare(choice1, choice2); function compare(choice1, choice2) < if(choice1 && choice2 === "rock" || "paper" || scissors) < alert("You pass"); >else

Could anyone give me a short explanation, why the if condition passes every value it gets? It never shows the mssage «Something went wrong».

7 Answers 7

I believe it shoud look like:

if ((choice1=="rock" || choice1=="paper" || choice1=="scissors") && (choice2=="rock" || choice2=="paper" || choice2=="scissors")) 

if((choice1 === "rock" || "paper" || "scissors") && (choice2 === "rock" || "paper" || "scissors")) < document.write("Form validated The Game can continue.") > else < document.write("Wrong. Access denied.") >That did not work either. strange.

It certainly doesn't work, because "paper" and "scissors" evaluate to true for the expression. It is like writing ((choice1==="rock")||("paper")||("scissors)).You can't compare several literals with a variable like that.

Источник

Javascript if with or conditions

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'); >

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'); >

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'); >

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.

Источник

javascript multiple OR conditions in IF statement

I think I'm missing something basic here. Why is the third IF condition true? Shouldn't the condition evaluate to false? I want to do something where the id is not 1, 2 or 3.

var if(id == 1) //true if(id != 1) //false if(id != 1 || id != 2 || id != 3) //this returns true. why? 

Then it should return false , I think? Sorry, I've been working all night so not able to think clearly.

@dku.rajkumar the var i = 1 was just an example. I need to do work on some 50 ids but skip where id is 1, 2, or 3.

6 Answers 6

With an OR (||) operation, if any one of the conditions are true, the result is true.

I think you want an AND (&&) operation here.

You want to execute code where the id is not (1 or 2 or 3), but the OR operator does not distribute over id. The only way to say what you want is to say

the id is not 1, and the id is not 2, and the id is not 3.

or alternatively for something more pythonesque:

The alternative checks for the index. Not if the value is in the array. Unlike in python where it checks for the value. array.indexOf(id) == -1 means that the id isn't in the array. use != for the opposite.

@NeilDesh, the trick is to have a partial identity mapping. It only works for small counting numbers so it's not generally useful. To represent the set (4) try [. 4] .

@denisb411 The partial identity array maintains an equivalence between key and value. You're right about .includes , but there was no such thing when I wrote that in 2012. Happy to accept an edit or up-vote a new answer.

Each of the three conditions is evaluated independently[1]:

id != 1 // false id != 2 // true id != 3 // true 

Then it evaluates false || true || true , which is true ( a || b is true if either a or b is true). I think you want

which is only true if the ID is not 1 AND it's not 2 AND it's not 3.

[1]: This is not strictly true, look up short-circuit evaluation. In reality, only the first two clauses are evaluated because that is all that is necessary to determine the truth value of the expression.

Источник

How to use OR condition in a JavaScript IF statement?

Note that if you use string comparisons in the conditions, you need to perform a comparison for each condition:

If you only do it in the first one, then it will always return true:

if ( var1 == "A" || "B" ) //don't do this; it is equivalent to if ("B"), which is always true 

The official ECMAScript documentation can be found here

Worth noting that || will also return true if BOTH A and B are true .

In JavaScript, if you're looking for A or B , but not both, you'll need to do something similar to:

Shouldn't be first phrase be "Worth noting that || will return true if EITHER var A OR var B is true" ?? It implies what you mentioned is (true | true) = true. which is common and understood.

@Murplyx: In most cases yes, but numbers outside the 32 bit range can fail. (Math.pow(2,32)-1) ^ 0; // -1 (success) . Math.pow(2,32) ^ 0; // 0 (failure)

if (A ? !B : B) <. would be a shorter substitute that wouldn't have the 32-bit limitation. Or maybe if (!A != !B) <.

@squint Why would a true or false ever be outside of the 32 bit range hence they are only 0 or 1, and btw if you compare numbers just use !!n to get the boolean value.

This says that if the answer is Yes yes or YeS than the same thing will happen

Yes, I discovered the hard way that you have to include each statement separately. I worked out that if (number === 1||2||3) is like while (true) ; the second and third conditions ask if 2 is 2 and/or 3 is 3. They always resolve as true to the statement always passes. There goes my plan to reduce the character count. Keeping the statements in parenthesis does make it easier to read though.

var choice = prompt("Do you choose rock, paper or scissors?").toLowerCase(); if (userChoice != ("paper"||"rock"||"scissors")) < console.log("Invalid Choice made"); >

var thingToTest = "B"; if (/A|B/.test(thingToTest)) alert("Do something!")

Here's an example of regular expressions in general:

var myString = "This is my search subject" if (/my/.test(myString)) alert("Do something here!")

This will look for "my" within the variable "myString". You can substitute a string directly in place of the "myString" variable.

As an added bonus you can add the case insensitive "i" and the global "g" to the search as well.

var myString = "This is my search subject" if (/my/ig.test(myString)) alert("Do something here");

You may also want to filter an IF statement when condition1 equals 'something' AND condition2 equals 'another thing' OR 'something else'. You can do this by placing condition2 in another set of brackets eg.

if (condition1 === 'x' && (condition2 === 'y' || condition2 === 'z'))

If condition2 is NOT in it's own brackets then condition1 has to be x AND condition2 has to be y for the function to trigger.

. but it will also trigger if condition2 is z, regardless of what condition1 is. Which may be okay depending on your use case, but something to be mindful of.

Источник

Читайте также:  Sum all integers java
Оцените статью