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
Related
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 ||.
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.
a = 1;
b = "1";
if (a == b && a = 1) {
console.log("a==b");
}
The Javascript code above will result in an error in the if statement in Google Chrome 26.0.1410.43:
Uncaught ReferenceError: Invalid left-hand side in assignment
I think this is because the variable a in the second part of the statement &&, a=1 cannot be assigned. However, when I try the code below, I'm totally confused!
a = 1;
b = "1";
if (a = 1 && a == b) {
console.log("a==b");
}
Why is the one statement right but the other statement wrong?
= has lower operator precendence than both && and ==, which means that your first assignment turns into
if ((a == b && a) = 1) {
Since you can't assign to an expression in this way, this will give you an error.
The second version is parsed as a = (1 && a == b); that is, the result of the expression 1 && a == b is assigned to a.
The first version does not work because the lefthand side of the assignment is not parsed as you expected. It parses the expression as if you're trying to assign a value to everything on the righthand side--(a == b && a) = 1.
This is all based on the precedence of the various operators. The problem here stems from the fact that = has a lower precedence than the other operators.
Because the order of operations is not what you expect. a == b && a = 1 is equivalent to (a == b && a) = 1 which is equivalent to false = 1.
If you really want to do the assignment, you need to use parentheses around it: a == b && (a = 1).
In if (a = 1 && a == b),
The operations to be first performed is 1 && a == b. 1 && the result of a == b is performed. The result of this && operation is assigned to a.
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();
}
}
I have a var a;
Its value can be NaN, null and any +ve/-ve number including 0.
I require a condition which filters out all the values of a such that only >=0 values yield a true in if condition.
What is the best possible way to achieve this, I do not wish to use 3 different conditions joined using ||
typeof x == "number" && x >= 0
This works as follows:
null -- typeof null == "object" so first part of expression returns false
NaN -- typeof NaN == "number" but NaN is not greater than, less than or equal to any number including itself so second part of expression returns false
number -- any other number greater than or equal to zero the expression returns true
Ohk ...But i actually found the ans ..
it is so Simple .
parseInt(null) = NaN.
So if(parseInt(a)>=0){} would do ...Yayyee
NaN is not >= 0, so the only exclusion you need to make is for null:
if (a !== null && a >= 0) {
...
}
This seems to work well:
if (parseFloat(x) === Math.sqrt(x*x))...
Test:
isPositive = function(x) { return parseFloat(x) === Math.sqrt(x*x) }
a = [null, +"xx", -100, 0, 100]
a.forEach(function(x) { console.log(x, isPositive(x))})
My best solution to filter those values out would be with 2 condition and it is like;
if(a!=undefined && a>=0){
console.log('My variable is filtered out.')
}
I am not sure but there is no single condition usage to make it.
I had the same problem some weeks ago, I solved it with:
if(~~Number(test1)>0) {
//...
}
http://jsfiddle.net/pT7pp/2/
Since you tagged jQuery, take a look at $.isNumeric()
if($.isNumeric(a) && a >= 0)