compare three variable using java script - javascript

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.

Related

Abbreviate check function

I'm just starting to learn javascript and i'm trying to figure out how to make this code shorter.
Right now, the check function evaluates if a = "admin" and after that if a = "manager".
Is it possible to do this evaluation in one line?
Kind of "if (a = "admin" or "manager") ..."
const valid = "User name valid";
const invalid = "User name invalid";
function check(a, b) {
if (a === "admin") {
return valid;
} else if (a === "manager") {
return valid;
} else if (b[0].toUpperCase() == b[0] && b.length > 4 && b.length < 10) {
return valid;
} else {
return invalid;
}
}
console.log(check("manager", "ikey"));
console.log(check("admin", "root"));
console.log(check("user", "ikey"));
console.log(check("user", "Mikey"));
Thanks!!
You can use the logical or operator to handle all valid cases together.
function check(a, b) {
if (a === "admin" || a === "manager" || b[0].toUpperCase() == b[0] && b.length > 4 && b.length < 10) {
return valid;
} else {
return invalid;
}
}
You can also simplify this to one statement using the ternary operator.
function check(a, b) {
return a === "admin" || a === "manager" || b[0].toUpperCase() == b[0] && b.length > 4 && b.length < 10 ? valid : invalid;
}
You should do it with or operator || like so:
if (a === "admin" || a === "manager" || (b[0].toUpperCase() == b[0] && b.length > 4 && b.length < 10))
return valid;
else
return invalid;

Is >= equal to > || === or > || == in JavaScript? [duplicate]

This question already has answers here:
Why `null >= 0 && null <= 0` but not `null == 0`?
(6 answers)
Closed 4 years ago.
Is the below if statement
if (a >= b)
Equal to this?
if (a > b || a === b)
Or is it equal to this?
if (a > b || a == b)
It is equivalent to if(a > b || a == b)
var a = "2";
var b = 2;
console.log(a >= b); // true
console.log(a > b || a == b); // true (== compares value)
console.log(a > b || a === b); // false (=== compares value and type)
You can test it in the console:
var a = 0;
var b = '0';
a == b; // true
a === b; // false
a >= b; // true
Ergo, >= is equivalent to > || ==.
The actual result depend on the use case if the typeof both a & b is same then (a >= b) is same as (a > b || a === b). This is because == is equality with type coercion
var a = "2";
var b = "2";
console.log(a >= b); // true
console.log(a > b || a == b); // true
console.log(a > b || a === b); // true
var a = "4";
var b = 4;
console.log(a >= b); // true
console.log(a > b || a == b); // true
console.log(a > b || a === b); // false
Actually the first one
if(a >= b)
is similiar to
if(a > b || a == b)
but not equals to
if(a > b || a === b)
because in this last one you are even comparing the type of both the operands.
Example:
x = "5"
console.log(x==parseInt(x)) will return true
console.log(x===parseInt(x)) will return false
So, == does not consider the types of operands.
It depends. If before the statement you had defined a or b with a different type,
if(a > b || a === b)
will return false if the first clause is not true. However if you didn't define a or b before both will have the same type and both expressions are equivalent.
You can understand "===" as
(a == b && sameType(a,b))

jQuery if condition 1 or condition 2 is true than

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

Multiple conditions in if statement on both sides of the logical operator

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'.

How to know which condition was true in an if statement?

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.

Categories

Resources