What I'm trying to is run some code if the number of input[type="checkbox"] is checked equal to the value of 2 or 3.
Here is an example of my JQuery:
if ($('input:checkbox:checked').length == 2 or 3) {
// run some code
}
Im not sure how to program it to understand whether the value is 2 or 3.
Any ideas?
Use the or operator ||
if ($('#id').length === 2 || $('#id').length === 3) {
// run some code
}
Please read up on Javascript logical operators. This is basic stuff.
Logical operators are used to determine the logic between variables or values.
Given that x = 6 and y = 3, the table below explains the logical operators:
Operator Description Example
========================================================
&& and (x < 10 && y > 1) is true
|| or (x === 5 || y === 5) is false
! not !(x === y) is true
Related
I already know this wouldn't work If I passed something like 0 or 1, but why wouldn't it work If it managed to work with 2 and 7.
I'm still new to Javascript programming so I'm just trying to figure out why adding
if(number = number % 2 == 0) or the other wouldn't work.
Here's the code:
function even_or_odd(number) {
if(number = number % 2 == 0) {
return "Even"
}else if(number = number % 2 !== 0) {
return "Odd"
}
};
= is an assignment operator. It assigns the value of the expression on the right-hand side to a variable on the left-hand side.
== is an equality operator. It tests the equality of the result of both the left and right-hand-side expression.
Since you're using = and inadvertently assigning number to the value of your expression on the right, it will always evaluate to a truthy value and return "Even". To fix, remove the number = from each of the expressions:
function even_or_odd(number) {
if(number % 2 == 0) {
return "Even"
}else if(number % 2 !== 0) {
return "Odd"
}
};
console.log(even_or_odd(0));
console.log(even_or_odd(1));
MDN has a great section on this in their if...else page:
It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:
if (x = y) {
/* do something */
}
If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:
if ((x = y)) {
/* do something */
}
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 ||.
This question already has answers here:
Double structural equality operators: if(a==b==c)
(2 answers)
Closed 8 years ago.
I've got 3 random numbers (in this specific case between 1 and 7 but it doesn't really matter).
I want to check whether I got "three of a kind" by using
if (x==y==z) {
code
}
The problem is that when x==y and z==1 x==y==z will return true. How do I check whether x, y and z actually got the SAME value?
Example: 5==5==1 will return true, how do I check for 5==5==5 specifically? (Excluding 5==5==1)
By doing a proper comparison:
x === y && y === z
// due to transitivity, if the above expression is true, x === z must be true as well
x==y==z is actually evaluated as
(x == y) == z
i.e. you are either comparing true == z or false == z which I think is not what you want. In addition, it does type conversion. To give you an extreme example:
[1,2,4] == 42 == "\n" // true
The problem is that when x==y and z==1, x==y==z will return true.
Yes, because x == y will be true, so you compare true == 1. true will be converted to the number 1 and 1 == 1 is true.
You should check with separate && operations
if(x == y && x == z){
//all are equal
}
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.
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))