multiple conditions in an if - else in javascript - javascript

I'm trying to make a program that only accepts a few values. So, if "e" variable is not 1 or 2 or 3, says that the number is not correct, but if the value is equal to those numbers, then the else part is run.
All of this may sound very begginer level and easy to implement, and it is, but I ran the code and EVERY vaule I set to "e" runs the if part.
Here is code:
var e;
e=parseFloat(prompt("Input e",""));
if(e!=1 || e!=2 || e!=3)
{
alert("put again E");
}
else
{
//whatever
}

In English you said "not 1 or 2 or 3", but that is written as !(e == 1 || e == 2 || e == 3); or, you could go with the logically equivalent "not 1, and not 2, and not 3", expressed as e != 1 && e != 2 && e != 3.
What you wrote is "not 1 or not 2 or not 3". If the value is 1, then it is not 2 (and also not 3), so "not 1 or not 2 or not 3" is still true. In fact, it is true for any value, because at least two of those (if not all three) will be true.

It's because || means or.
if(e!=1 || e!=2 || e!=3)
If you input e = 1 you will have
if(false OR true OR true)
which of course, evaluates to true.
You want &&, which means and, resulting in:
if(e!=1 && e!=2 && e!=3)
if you want to maintain your code structure. Or you could take the advice of the others, and put your "else" code into the "if" block and use ==.

Since e can't have the value of 1,2 and 3 simultaneously, your condition is always going to evaluate to true. your version reads
if the value is different from 1 or different from 2 or different from 3 then do this.
So you will need to change it to something that reads more like
if the value is not either 1 or 2 or 3 then
if(!(e == 1 || e == 2 || e == 3)){...}
or you could do
if(e != 1 && e != 2 && e != 3){...}
which would read
if the value isn't 1 and isn't 2 and isn't 3
The result of those two options would be the same.

You should use == rather than != like:
if(e==1 || e==2 || e==3)//then re enter value
With your if, you mean if e is neither of 1,2,3 then ask user to reenter the value.

The reason is simple. If for example you input the value 1 the first part of your condition returns false, but the other 2 parts return true, then the condition can be read like this:
if( false || true || true ) {
...
}
So no matter what input, there will always be 2 true values against a false value. To get what you want, use && instead of ||.

Related

Whats the difference between (a==1 || b==1) and ((a || b)==1)

Whats the difference between (a==1 || b==1) and ((a || b)==1)
this code block works right
if(userName==="" || userAge==="" ){
addErrorBool(true);
return;}
but this one not
if((userName || userAge)==="" ){
addErrorBool(true);
return;}
whats does the second one do?
a || b will evaluate to a, if a is truthy, otherwise it'll evaluate to b. So ((a || b)==1) will take whichever value that was and compare it against 1.
For example
(0 || 5) == 1
// equivalent to
(5) == 1
(1 || 2) == 1
// equivalent to
(1) == 1
For what you want, use .some instead, if you want to keep things DRY.
if ([userName, userAge].some(val => val === '')) {
addErrorBool(true);
return;
}
And then you can add as many items to the array .some is called on that you want.
(userName || userAge)==="" means:
(userName || userAge): if userName is truthy, use this value. Otherwise use userAge
==="": compare whichever object was chosen above, and compare that this is a string with no contents.
userName==="" || userAge==="" means:
userName==="": compare userName to see if it is a string with no contents
if it is, the result is true, otherwise:
userAge==="": compare userAge to see if it is a string with no contents
if it is, the result is true, otherwise the result is false

When should you use parentheses inside an if statement's condition?

I have a if condition like so:
$(document).ready(function(){
var name = 'Stack';
var lastname = 'Overflow';
if( name == 'Stack' && lastname == 'Overflow' )
alert('Hi Stacker!');
});
So my alert is fired...
If I put my condition inside a brackets like this:
$(document).ready(function(){
var name = 'Stack';
var lastname = 'Overflow';
if( (name == 'Stack') && (lastname == 'Overflow') ){
alert('Hi Stacker!');
}
});
My alert is also fired...
My question is: When and why I should use parentheses inside my if condition? Thank you!
There is no much difference in your example.
You can read that for reference
Operator Precedence (JavaScript)
You use it to force associations, in your example this won't change anything. But consider this case:
A and B or C
is a lot different from
A and (B or C)
Here you would be preventing the expression from being understood as (A and B) or C which is the natural way javascript and maths do things.
Because of operator precedence :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
you'd better read this if you want more details
But basically == (equality) weights more than && (logical-and) , so A == B is evaluated before C && D given
C <- A == B
and
D <- E == F
so adding parenthesis to C or D dont matter,in that specific situation.
Brackets can be used, if multiple conditions needs to be checked.
For ex: User is also a Stacker if full name is 'StackOverflow' then add another condition with 'Or' operator.
if(((name == 'Stack') && (lastname == 'Overflow')) || FullName =='StackOverflow')
As you can see, name and last name are placed inside one bracket meaning that it gives a result either true or false and then it does OR operation with FullName condition.
And having brackets around name, lastname and fullname fields are optional since it doesn't make any difference to the condition. But if you are checking other condition with FullName then group them into bracket.
Brackets are never required in such situations.
Of course, try to read first solution (without) and second solution (with). Second one it's clear, fast-readable and easy to mantain.
Of course if you have to change precedence (in this case you just have an AND condition, but what if you need and AND and an OR? 1 and 2 or 3 priority changes between "(1 and 2) or 3" - "1 and (2 or 3)"
Brackets () are used to group statements.
Ex - if you have an expression '2 + 3 * 5'.
There are two ways of reading this: (2+3)*5 or 2+(3*5).
To get the correct o/p based on operator precedence, you have to group the correct expression like * has higher precedence over +, so the correct one will be 2+(3*5).
first bracket requires for complex condition to ensure operator precedence correctly. lets say a example
var x=1,y=1,z=0;
if(x==0 && y==1 || z==0)
{
//always true for any value of x
}
what will happen here
(0 && 1 ||1) ----> (0 ||1)----->1
&& has high precedence over ||
if(x==0 && (y==1 || z==0)) alert('1');
{
//correct way
}
if you do not use (y==1 || z==0) bracket the condition always will be true for any value of x.
but if you use (..) the condition return correct result.
Conditional statements can be grouped together using parenthesis. And is not only limited to if statements. You can run the example below in your Chrome Developer Tools.
Example 1:
Console Execution
false && false || true
// true
flow
false && false || true
| | |
|________| |
| |
| |
false or true
| |
|_________________|
|
|
true
Example 2:
Console Execution
false && (false || true)
// false
flow
false && (false || true)
| |
|______________|
|
|
false
Helpful resources for playing around with JSInterpreter and AST's:
https://neil.fraser.name/software/JS-Interpreter/
https://esprima.org/demo/parse.html#
Consider the statement
if( i==10 || j == 11 && k == 12 || l == 13)
what you would want is if either i is 10 or j is 11 And either k is 12 or l is 13 then the result shouldbe true, but say if i is 10, j is 11, k is 10 and l is 13 the condition will fail, because the fate of equation is decided at k as aoon as && comes in picture. Now if you dont want this to happen the put it like this
if( (i==10 || j == 11) && (k == 12 || l == 13))
In this ORs will be executed first and the result will be true.

javascript OR (||) not returning expected result

I have a field that needs to accept input values for city/state in several formats, including City ST (Chicago IL), City, ST (Chicago, IL), and City,ST (Chicago,IL - no space between). We're testing for a two-letter state code after either a comma or the last instance of a space (because city names can have spaces.)
I have the following code that fails values that should pass, and vice versa.
var x = "Chicago,IL";
if (
(isNaN(x) && x.indexOf(' ') < 0 && x.split(" ").pop().length > 2) ||
(isNaN(x) && x.indexOf(',') > 0 && x.split(",").pop().trim().length > 2)
) {
alert("fail");
}
else {
alert("pass");
}
(Fiddle here)
So what my code SHOULD do is fail if 1) the value is not a number AND contains at least one space AND there are more than 2 characters after the final space, or 2) the value is not a number AND it contains a comma AND there are more than 2 characters after the comma (I'm trimming out a potential space after the comma.)
What's actually happening is, it's passing these values:
Chicago IL
Chicago, IL (with a space, even though it's trimming the space)
But failing Chicago,IL (entered initially without a space.) The reason I think it's a problem with the OR (II) is that if I remove the first part and test only for the value containing a comma, Chicago,IL passes. I thought that OR conditionals only return false if both sides of the OR are false, but that doesn't seem to be the case here.
I'm sure this is a really simple thing, but I've been staring at it for way too long and just can't see it.
That seems too complicated. If you are going to do it like that, use multiple statements (so that they can be reasoned about easier). Anyway, here is my "solution" which, admittedly, does not try to address why the original didn't work as expected:
var cityState = /^\w+(?:,\s*|\s+)\w{2}$/;
if (cityState.test(input)) {
// good
}
To accept either "City Name, State" or "City Name State", consider this (more complex) regular expression. The key to this working is the lazy modifier and the anchoring.
function isValidState (st) {
// This could be turned into an appropriate whitelist, and may include
// things like "Illinois".
return st.length == 2;
}
function parseCityState (cs) {
var match = cs.match(/^\s*(\w.*?)\s*([, ])\s*(\w+)\s*$/) || [];
var city = match[1];
var commaUsed = match[2] == ',';
var state = match[3];
if (city && state && isValidState(state)) {
return {city: city, state: state, commaUse: commaUsed}
} else {
return undefined;
}
}
Now, if you're interesting in why the original fails, consider this updated analysis for why "Chicago, IL" fails. Let x = "Chicago, IL", then:
isNaN(x) -> true
x.indexOf(' ') -> >0
x.indexOf(',') -> >0
x.split(' ') -> ["Chicago,", "IL"]
x.split(',') -> ["Chicago", " IL"]
And substituting:
true && (>0 < 0) && ["Chicago,", "IL"].pop().length > 2
||
true && (>0 > 0) && ["Chicago", " IL"].pop().trim().length > 2
Evaluation, again (note that the test for "no space" fails the first expression line because there is a space):
true && false && "IL".length > 2
||
true && true && "IL".length > 2
And evaluation again (note that both expression lines fail because "IL" only has a length of 2):
true && false && false
||
true && true && false
And ultimately this rejects the input:
false || false -> false
This is true:
I thought that OR conditionals only return false if both sides of the
OR are false
About this:
if I remove the first part and test only for the value containing a comma, Chicago,IL passes
In your fiddler example, commenting out the first test prints "fail", which implies that it is evaluating to true.
There is no problem with JS ORs. But what is what you were expecting?
I think you have a mistake on this line
x.indexOf(' ') < 0
should be
x.indexOf(' ') > 0
But if I were you, I'd use a regular expression:
var info = 'South Beach, FL';
var regex = /\w+(\w+ \w+)*\s*,\s*[a-zA-Z]{2}/;
alert(regex.test(info) ? 'Valid' : 'Invalid')

Using and (&&) and or (||) together in the same condition in JavaScript

I'm wondering how to combine and (&&) with or (||) in JavaScript.
I want to check if either both a and b equal 1 or if both c and d equal 1.
I've tried this:
if (a == 1 && b == 1 || c == 1 && d == 1)
{
//Do something
}
But it doesn't work.
How can I write this condition correctly?
&& precedes ||. == precedes both of them.
From your minimal example I don't see, why it doesn't achieve your desired effect. What kind of value types do a–d have? JavaScript might have some non-obvious type coercion going on. Maybe try comparing with === or convert to numbers explicitly.
Side note: many lint tools for C-like languages recommend to throw in parentheses for readability when mixing logical operators.
Operator Precedence can be overridden by placing the expression between parenthesis.
if ((+a == 1 && +b == 1) || (+c == 1 && +d == 1)) // Use brackets to group them
{
// your code
}
This will prevent you from such cases like if(0&&0 || 1&&1) .
Well now that I've finished telling everybody else (except David) why their answers are wrong, let me give them the same chance to hassle me.
Your existing code as shown should already do what you seem to be describing. But is it possible that when you say:
"I want to check if either both a and b equals 1 or if both c and d equals 1."
...your use of the word "either" mean that you want to check if one and only one of the following conditions is true:
both a and b are 1, but c and d are not both 1
both c and d are 1, but a and b are not both 1
That is, you want one pair of variables to be 1, but you don't want all four variables to be 1 at the same time?
If so, that is an exclusive OR operation, which in JS is the ^ operator:
if ((a == 1 && b == 1) ^ (c == 1 && d == 1)) {
Note that unlike with a logical OR || operator, you have to add parentheses around the AND && parts of the expression because ^ has higher precendence. (^ is actually a bitwise operator, but it will work for you here since the operands you'd be using with it are all booleans.)
place some extra brackets to differentiate the and n or conditions
if ((a == 1 && b == 1) || (c == 1 && d == 1))

How to have multiple 'and' logical operators and an 'or' logical operator

It is slightly hard to explain but I want to do something that looks like this:
if(a === 4 && b === true && c === "words" || "numbersandwords")DoSomething();
but it ends running without it matching the first operators. I want to know how to have the last operator except 2 different inputs while still making sure the other criteria are met before running.
You just need to use parentheses, e.g.:
if(a == 4 && b == true && (c == "words" || c == "numbersandwords")) { DoSomething(); }
Just use a few brackets to separate your or parts and the and parts, and add the c === before the last string. Without that equality part at the end, the 'numbersandwords' string always equates to true.
if(a === 4 && b === true && (c === "words" || c === "numbersandwords")){
DoSomething();
}
In JavaScript, like other languages, every operator (like && and ||) has a precendence that determines the order in which it's evaluated. && has higher precedence than ||, so it's evaluated first. Therefore, every term on the left is anded together. Even if they are all false, however, the overall result is true because it's ored with "numbersandwords", which evaluates to true (as does everything except 0, -0, null, false, NaN, undefined, or the empty string). The first thing you need to do is actually compare something (presumably c) to it. Then you can change the order of evaluation using parentheses, which has higher precedence than anything else:
if(a === 4 && b === true && (c === "words" || c === "numbersandwords")) DoSomething();
Alternatively, you can break the test up into several if statements if you may want to eventually do something slightly different based on the value of c (or it just better expresses your intent):
if(a === 4 && b === true)
{
if(c === "words" || c === "numbersandwords")
{
DoSomething();
}
}

Categories