Using multiple logical "or" operators - javascript

Other than using a switch statement (or writing if(x === 2 || x === 3 || x === 4) etc), is there any way to implement multiple "or" (||) operators?
E.g.:
if(x === 2 || 3)
alert("Yes");
This alerts for every value of x

The closest you can probably come is to do something like this:
if ([2,3].indexOf(x) > -1){
}
DOCS
Of course that will require a shim for IE 8 and below, if that's an issue for you.

Standard approach for large number of choices is to use dictionary/hash set/hash table depending on language.
For JavaScript both array and object would work:
var isPresent = [];
isPresent[2] = true;
isPresent[43] = true;
if (isPresent[x])...
For small number of items Adam Rackis' answer with linear search is much more readable
[2,3].indexOf(x)

Related

Use .indexof to Check for Multiple Strings with Array [duplicate]

This question already has answers here:
How to check if a string contains text from an array of substrings in JavaScript?
(24 answers)
Closed last year.
I am attempting to embed a chat widget if utm_source=VALUE (any of these values)
Here is the surrounding code:
var ref1 = document.referrer;
IF STATEMENT HERE
{
alert("Welcome to Ellas Bubbles");
s1.src='https://embed.tawk.to/620675459bd1f31184dc28c0/1frkjk5mj';
}
You can test it here: https://ellasbubbles.com
I have tried the following, which is only working on 'ccov':
if ((ref1.indexOf('ccov') || ref1.indexOf('top10') || ref1.indexOf('cenf') || ref1.indexOf('aip') || (getcookie('track-page-1').indexOf('ccov')>-1) || (getcookie('track-page-1').indexOf('top10')>-1) || (getcookie('track-page-1').indexOf('cenf')>-1) || (getcookie('track-page-1').indexOf('aip')>-1)) > -1)
I have also tried this:
if ((ref1.indexOf('ccov' || 'top10' || 'cenf' || 'aip') || (getcookie('track-page-1').indexOf('ccov' || 'top10' || 'cenf' || 'aip')>-1)) > -1)
{
s1.src='https://embed.tawk.to/620675459bd1f31184dc28c0/1frkjk5mj';
}
Which is also only working on the first value, 'ccov'.
I have also tried this:
if ((ref1.indexOf('ccov', 'top10', 'cenf', 'aip') || (getcookie('track-page-1').indexOf('ccov', 'top10', 'cenf', 'aip')>-1)) > -1)
Which is also only working on the first value
Is there a better way to go about this?
I think your statements are incomplete. Before each || you need to condition to be satisfied. I’m writing on my phone so sorry this isn’t as specific but you need the >-1 before every ||. So instead of
X || Y < z
I think You need
X < z || y < z.

What can I do to make code be executed while the answer is one of a multiple conditions?

I tried to make that a code runs when x, determinated by a prompt is one of the four answers. With only one possibility it works well, but when I add more using && the program do nothing. (At the end of the program i put a break to execute the code only one time)
That's a short version of how the programm works...
var x = prompt("Ready?");
while(x == "yes"){
window.alert("...Example...");
break;
}
And how I want to make it but doesn't works...
var x = prompt("Ready?")
while(x == "Yes" && x == "yes" && x == "yeS" && x == "YES")
window.alert("...Example...");
break;
}
How can I do to make it works?
I would just use .toLowerCase() before the comparison so you don't have to deal with all different ways to capitalize a word.
var input = prompt("Ready?");
var x = input.toLowerCase();
while( x == "yes" )
window.alert("...Example...");
break;
}
Then again, if you only need yes or no as options, I'd use a window.confirm instead of a window.prompt.
Edit: Hmm, if the question is that the answer HAS to be yes written in one of those 4 ways, I'd go for the array approach so you can add other options later on:
var allowed_answers = [ 'yes', 'Yes', 'yeS', 'YES' ];
if ( allowed_answers.includes( x ) ) {
}
Use || instead of &&, and there's no need for a while statement, use if instead:
var x = prompt("Ready?")
if (x === "Yes" || x === "yes" || x == "yeS" || x == "YES") {
window.alert("...Example...");
}
|| means “or”, i.e. at least one of the conditions has to be true. If you use “and”, it means all of the conditions need to be true, which cannot possibly work.
Maybe you're trying to do this
do{
var x = prompt("Ready?").toLowerCase();
//toLowerCase() method convert (YES, Yes, yeS, etc) to (yes)
if(x === "yes"){
//If the condition is true, the loop breaks
window.alert("...Example...");
break;
}
}while(true)

Multiple OR conditions for an IF statement

Am I doing the multiple OR conditions for an IF statement the right way?
var A0minWidth = 841;
var A0minHeight = 1189;
var A0minWidthBleed = 847;
var A0minHeightBleed = 1195;
UploadedDocNameHeightMM = //(get it from the database)
UploadedDocNameWidthMM = //(get it from the database)
if(UploadedDocNameHeightMM < parseFloat(A0minHeight) || UploadedDocNameWidthMM < parseFloat(A0minWidth) || UploadedDocNameWidthMM > parseFloat(A0minWidthBleed) || UploadedDocNameHeightMM > parseFloat(A0minHeightBleed))
{
//do this
alert ("Yes! one of those.")
}
Help!
It depends on what your code is supposed to do of course, but syntactically this is correct - e.g. no need to wrap each each expression that is an operand to the logical-OR operators in parentheses like this:
if ((UploadedDocNameHeightMM < parseFloat(A0minHeight)) || (UploadedDocNameWidthMM < parseFloat(A0minWidth)) || (UploadedDocNameWidthMM > parseFloat(A0minWidthBleed)) || (UploadedDocNameHeightMM > parseFloat(A0minHeightBleed)))
{
alert("Yes! one of those.");
}
Also, the || operator will short-circuit evaluate. Basically it will not evaluate expressions to the right of any expression that evaluates to true.
For more information on || and other JavaScript logical operators including examples check out Mozilla's overview or search on JavaScript logical operators.
The syntax is correct.
However:
parseFloat is not necessary here
Are you sure the two first tests are correct (==> Don't you need to check if UploadedDocNameHeightMM > A0minHeight instead of < ?)

Detect if a number is between 2 others?

What's the best way to detect if a number, is between two other numbers? Is there already a function to do this in the Math object?
There is no specific function, but you can do it like this:
lowNumber < yourNumber && yourNumber < highNumber
Though the code solution is fairly obvious, if you're going to use it a lot, you may want to implement it on Number.prototype for convenience:
Number.prototype.inRange = function( a,b ) {
var n = +this;
return ( n > a && n < b );
};
So you'd use it like this:
(5).inRange( 3, 7 ); // true
Example: http://jsfiddle.net/dTHQ3/
Um if it is greater than one and less than the other.
var num1 = 3;
var num2 = 5;
var x = 4;
var isBetween = (num1 < x && num2 > x);
if ( yournumber < highNumber && yournumber > lowNumber ){
// do something
} else {
// do something else
}
The only optimized way to do this is to guess which is more likely: Is the number your checking more likely to be lower than the lower bound, or is it more likely to be higher than the upper bound?
With this in mind, you can take advantage of short circuiting by placing the more likely failure check first (if it fails that, it won't test the less likely criteria). This is the only way to optimize it.
Even this will save you the smallest amount of time that is most likely not going to be noticed. Perhaps if you were making this check millions of times, you might save a fraction of a second over the alternative.

Shorten JS if or statement [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Is there anyway to shorten something like this in Javascript: if (x == 1 || x == 2 || x == 3 || x == 4) to something like if (x == (1 || 2 || 3 || 4)) ?
You can use use Array.indexOf
[1,2,3,4].indexOf(x) !== -1
You can also use objects as some kind of hash map:
//Note: Keys will be coerced to strings so
// don't use this method if you are looking for an object or if you need
// to distinguish the number 1 from the string "1"
my_values = {1:true, 2:true, 3:true, 'foo':true}
my_values.hasOwnProperty('foo')
By the way, in most cases you should usi the "===" strict equality operator instead of the == operator. Comparison using "==" may do lots of complicated type coercion and you can get surprising results sometimes.
If your cases are not that simple to be expressed by this:
if (1 <= x && x <= 4)
You could use an array and indexOf:
if ([1,2,3,4].indexOf(x) > -1)
Note that indexOf might need to be re-implemented.
Not without writing a function that takes an array as an input and returns true/false, or some sort of array search. It would be hard to maintain/other devs to read. And it would be significantly slower. So just stick with the semantically correct longer version.
Also a good way to see if anything can be shortened significantly is to run it through the close compiler and see what it comes out with.
How about:
if (x > 0 && x < 5) {
}
You could write a function:
function isAny(x) {
for (var i = 1; i < arguments.length; ++i)
if (arguments[i] === x) return true;
return false;
}
Then you can say:
if (isAny(x, 1, 2, 3, 4)) { /* ... */ }
(Whether to use "===" or "==" would depend on the exact semantics you want.)

Categories

Resources