How can I know which condition in an if statement in JavaScript was true?
if(a === b || c === d){ console.log(correctValue) }
How can I know if it was either a === b or c === d?
Edit: I wanted to know if there was any way of doing this besides checking each condition on it's own if statement.
You can't.
If it matters, it needs to be two different conditions.
if (a == b) {
// it was a == b
return true;
}
if (c == d) {
// it was c == d
return true;
}
Note that even so, you won't know if both or just one of these conditions is true.
If you want to know this as well, you'll want an additional if:
if (a == b && c == d) {
// a == b and c == d
} else if (a == b) {
// just a == b
} else if (c == d) {
// just c == d
}
return (a == b || c == d);
If you really need to know which condition was true, just test them separately:
if(a == b) {
console.log("a == b");
return true;
} else if(c == d) {
console.log("c == d");
return true;
}
Alternatively, you might prefer something like this:
var result;
if ((a == b && result = "a == b") || (c == d && result = "c == d")) {
console.log(result);
return true;
}
This code is effectively equivalent to the former, however, I wouldn't recommend using this in a production system. It's much harder to read and guess the original intent of the codeāit's likely that the person reading this after you would think the result = was supposed to be result ==. Also note that because empty strings are falsy, you must ensure that the string you assign to result is never empty, otherwise it would never enter the if-block.
You can try something like this:
if(e = (a === b) || (f= c === d)){ console.log(e, f, correctValue) }
Then You can check whether e or f is true, then make your changes.
I don't know about memory leak or something for this but yeah it works.
Related
I was looking through moment.min.js when I ran into an expression that looked like this:
return A ? B : C === D ? E : F
Literally, I would read that as when this function is called, return the result of if A then B, else C, must strictly equal if D then E, else F, but even if that's correct, I am not sure exactly what that does.
How is that read and what would the expression do?
return A ? B : ((C === D) ? E : F);
Maybe it's easier to understand with those parentheses (evaluates to the same). The exact representation of the code above with if-else statements are:
if (A == true) {
return B;
} else {
if (C === D) {
return E;
} else {
return F;
}
}
I could also write return (A ? B : ((C===D) ? E : F)); The point is that if A wont evaluate to true, then another ternary operator is evaluated. Those parentheses just separate them from the other one, but they are absolutely not neccessary.
return (A ? B : C) === (D ? E : F); In this case we compare the evaluation of two ternary operators, and return it's result, which is a completely different story.
It test if A is truthy (a number !== 0, a not empty string, an object, not null, not undefined) then return B. If not, then check if C is strict equal D, return E otherwise F
if (A) {
return B;
} else if (C === D) {
return E;
} else {
return F;
}
Apply syntax precedence, to get:
return (A ? B : ((C === D) ? E : F))
Is A truthy? Yes? Great, return B.
Oh, it's not? Then depending on whether C is strictly equal to D, return either E or F.
The author should not have written such confusing shorthand, and this question is why.
I am trying to alert "yes" if ether of the conditions in my if statement are true:
var a = 2;
var b = 1;
if (a = 1 or b = 1 ) {
alert('yes');// should alert in this case
} else {
alert('no');
}
https://jsfiddle.net/90z7urvd/1/
What do I use for the if, if this is possible?
a = 1 will set the value 1 to variable a. It is not doing a comparison. For comparison, you use === or ==
=== (Identity operator) is the correct way to compare if both the types are same.
if (a === 1 || b === 1 ) {
=== operator won't do the type conversion before the comparison while == does the type conversion before the comparison.
For your or case, You may use || operator
var bootresul = someExpression || anotherExpression
Corrected code
var a = 2;
var b = 1;
if (a === 1 || b === 1 ) {
alert('yes');
} else {
alert('no');
}
You are assiging value rather then comparing
Try like this
if (a == 1 || b == 1)
To compare strictly use ===
Like this
if (a === 1 || b === 1)
JSFIDDLE
you can do this
var a = 2;
var b = 1;
if ((a == 1) || (b == 1 )) {
alert('yes');// should alert in this case
} else {
alert('no');
}
the == is one of the relational operator for checking equality and || is a logical operator that is a notion of logical OR
use this to compare just values
if (a == 1 || b == 1){
}
OR use this to compare values and type of variable
if (a === 1 || b === 1){
}
note : == will just check of values and === this will check value with type of variable
var a = 2;
var b = 1;
if (a == 1 || b == 1 ) {
alert('yes');// should alert in this case
} else {
alert('no');
}
I think you were doing assignment instead of comparison
Try using this:
if(a === 1 || b === 1){
alert('YES!')
}else{
alert('NO!')
}
OR you can use ternary operator condition instead of if else
(a == 1 || b == 1) ? alert('YES!') : alert('NO!')
This question already has answers here:
chaining double equals == returns false [duplicate]
(3 answers)
Closed 7 years ago.
Let's var a = "first", b = "second", c = "first";.
Expression a == c returns true, (of course!); a == c is true too.
Then why does a == a == c return false?
Example
var a = "first", b = "second", c = "first";
write( a != b != c );
write( a == b != c );
write( a == b == c );
write( a != b == c );
write("");
write( a == a == c );
// -------------------
function write(val) {document.querySelector("console").innerHTML += "<hr noshade size='1px' color='#eee'>" + String(val);}
<console></console>
Because what is really happening is this:
(a == a) == c
Which is really just:
true == "first"
See Operator Precedence.
Because it goes from left to right, one == at a time and the result of each previous == operation is a boolean:
(a == a) === true
(true == c) === false
You need to do:
a == a && a == c
or better yet (since this is JavaScript):
a === a && a === c
Alternatively, can write in CoffeeScript, which will translate:
a == a == c
into
(a === a && a === c);
for you.
a == c returns a boolean (true).
Since a is not a boolean, it cannot possibly equal a == c.
Hi I have three dynamic variable
my below code is working to check if all are equal
if ((a == b) && (b == c)) {
// they're all equal ...
}
But, I want to create a function passing three variable to check if any one variable is equal to other variable.
a=1;b=2;c=1;
isEqual = compareVariable(a,b,c);
here isEqual should be true .
How to create this function
function compareVariable(a,b,c) {
return a==b || b==c || c==a;
}
Try using it like this:
function compareVariable(a,b,c){
var a = a;
var b = b;
var c = c;
if ((a == b) && (b == c)) {
return true
}
else
{
return false;
}
}
compareVariable(1,2,3);
function compareVariable(a,b,c)
{
if ((a == b) || (b == c) || (a == c) ) {
alert("equal");
// they're all equal ...
}
else
{
alert("notequal");
}
}
Try this:
function compareVariable(a,b,c){
if ((a == b) || (b == c) || (a == c)) {
return true
// any or all equal
}
else
{
return false;
// if none of two is equal
}
}
To create a function you need to use the reserved keyword 'function' followed by the name of the function. In this case:
function compareVariable(a,b,c) {
return ((a == b) || (b == c) || (a == c));
}
This function will take your three variables and return boolean true if all the variables are the same.
I was experimenting with having multiple arguments in an if statement on both sides of the logical operator. I first started with the || operator, which worked as expected:
var a = 'apple', b = 'banana', c = 'cherry';
if (a == 'banana' || a == 'apple' || b == 'banana' || b == 'apple') {
console.log('example 1') // returns
}
if ((a || b) == 'banana' || (a || b) == 'apple') {
console.log('example 2') // returns
}
if (a == ('apple' || 'banana') || b == ('apple' || 'banana')) {
console.log('example 3') // returns
}
if ((a || b) == ('apple' || 'banana')) {
console.log('example 4') // returns
}
So far, no unexpected results.
However, when following a similar structure when replacing the || operator for the && operator, things don't quite work as I expect them to.
if ((a == 'banana' && b == 'apple') || (a == 'apple' && b == 'banana')) {
console.log('example 5') // returns
}
if (((a || b) == 'banana') && ((a || b) == 'apple')) {
console.log('example 6') // DOESN'T RETURN
}
if ((a || b) == 'banana') {
console.log('example 6a') // DOESN'T RETURN - consistent with example 6
}
if ((a == ('apple' || 'banana')) && (b == ('apple' || 'banana'))) {
console.log('example 7') // DOESN'T RETURN
}
if (a == ('apple' || 'banana')) {
console.log('example 7a') // returns - inconsistent with example 7
}
if (b == ('apple' || 'banana')) {
console.log('example 7b') // DOESN'T RETURN - inconsistent with example 7a
}
if ((a && b) == ('apple' || 'banana')) {
console.log('example 8') // DOESN'T RETURN
}
if ('apple' == (a || b) && 'banana' == (a || b)) {
console.log('example 9') // DOESN'T RETURN
}
Now, I am wondering: is there a flaw in my logic or can it just not be done this way? My aim is to write these if statements as short as possible, for the purpose of readibility and maintainability. Clearly I am just exploring possibilities.
Does anyone know any way to go about this? Especially example 7/7a/7b seems peculiar to me because it yields inconsistent results despite a similar structure [Fiddle]
The Logical OR operator doesn't work in a way you're looking for.
Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.
MDN
One alternative way could be make use of array's indexOf method. Just be aware it will return the index of the array element, so 0 could be a valid value also. In order to make our if statement works as expected, we have to use 0 <= ... like this:
if ( 0 <= ["apple","banana"].indexOf(a) ) { ... }
The other thing you can do is using in operator. Also as it checks only against the keys, you can leave the values empty like this:
if ( a in { "apple": "", "banana": "" } ) { ... }
If you have lot's of options, obviously it's better to do the following:
var options = {
"apple": "",
"banana": ""
}
if ( a in options ) { ... }
Personally I think with just two options to check, this will be more readable for a human-eye to go for two separated checks, and I think in your examples you don't really need to shorten the if statements as they're already quite short and readable in my opinion.
if ( "apple" === a || "banana" === a ) { ... }
If you want a clean way to check if a variable equals any of a number of other variables, try using a function like this:
http://jsfiddle.net/aYRmL/
function equalsAny (first) {
return !![].slice.call(arguments, 1).filter(function (val) {
return first === val;
}).length;
}
The first argument is the one being compared to the rest. Use it like this:
var a = 'banana', b = 'orange';
equalsAny(a, 'banana', 'apple'); // returns true
equalsAny('orange', a, b); // returns true
The first one above accomplishes what you were trying to do with a == ('banana' || 'apple'). The seconds accomplishes what you were trying to do with (a || b) == 'banana'.
As an alternative solution you can use some or every:
var __slice = [].slice;
function any(a) {
return __slice.call(arguments,1).some(function(x) {
return a === x;
});
}
function all(a) {
return __slice.call(arguments,1).every(function(x) {
return a === x;
});
}
And use like:
// Instead of:
// if (a == 'banana' || a == 'apple' || a == 'orange')
if (any(a, 'banana', 'apple', 'orange')) {
...
}
// Instead of:
// if (a == 'banana' && b == 'banana' && c == 'banana')
if (all('banana', a, b, c)) {
...
}
(a || b) == 'banana' always will be false because (a || b) will return a Boolean witch is not equal to a string
UPDATE :
did some testing (a || b) always returns the first operand (a in this case) witch is 'apple' and not equal to 'banana'.
|| and && will give excepted result only if the both operands are Boolean or can be cased to Boolean.
The way it's working is that a && b and a || b are always set to the value of one of the variables. a && b will always be set to the value of b unless a is false, in which case the answer must be false. Similarly a || b will be set to the value of a, unless a is false, in which case it will be set to the value of b. As elclanrs mentioned, this is because of short-circuit evaluation -- the first operand may determine the result, in which case there's no point in looking at the second operand.
When both a and b are strings, they will never be false unless the string is zero-length. So a || b will be 'apple' in your case, and a && b will be 'banana'.