Comparing same value against numerous others in an if-statement [duplicate] - javascript

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Closed 5 years ago.
This one is probably fairly straightforward, but I haven't succeeded in finding an answer as of yet. Anyway, what I want to do is compare one value against a group of others, and run the script if it matches one of them. Here's the verbose version of I want to do, which works fine, but I'm assuming there's a smarter, less verbose way to achieve this?
function updatePosition(e) {
if((e.target.innerHTML == 1) || (e.target.innerHTML == 4) ||
(e.target.innerHTML == 7)) {
console.log(e.target.innerHTML)
}
}

You can store all the valid comparison inside an array. Then you can use Array#Find() to get a matching value. If there is no matching value, you will get undefined
function updatePosition(num) {
let validNumbers = [1,4,7];
console.log(validNumbers.find(valid => valid === num));
}
updatePosition(4);
updatePosition(9);

Related

How do I exit an Array.forEach loop early? [duplicate]

This question already has answers here:
Short circuit Array.forEach like calling break
(30 answers)
Closed 3 years ago.
I'm working on a homework problem using JavaScript. I have a solution that currently works, but I am sure that it is not the most efficient way to do it. I am iterating over an array to check if any element meets a certain condition. But there doesn't seem to be a way to exit the forEach() function early. In other languages, I have used break to quit a forEach loop early. Does something similar exist in JavaScript?
My code (simplified for this question):
let conditionMet = false;
numbers.forEach((number) => {
if (number % 3 === 0) {
conditionMet = true;
// break; <-- does not work!
}
});
Rather than using Array.forEach, you can use Array.some (see docs). This function iterates over the elements of the array, checking to see if any element meets a certain condition. If an element is found that meets the condition, the function stops iteration, and returns true. If not, the function returns false. This means that you can also skip the step of initializing conditionMet to false.
Your code can therefore be simplified as:
let conditionMet = numbers.some(number => (number % 3 === 0));
You can’t break .foreach() loop unless through an exception
So you can choose another tool like a simple for loop.

Is there a way in javascript to avoid repeating the same variable in a logic expression? [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
How to shorten my conditional statements
(15 answers)
Closed 3 years ago.
For example, instead of:
if (ext === "_st" || ext ==="_mt" || ext === "_00" ){
//do something
}
I would intuitively expect that the following also works:
if (ext === ("_st" || "_mt" || "_00" )){
//do something
}
But that doesn't work.
Is there a way to avoid repeating the same ("ext" in this case) variable for more compressed and efficient code?
UPDATE: I did a search before asking and none of the "duplicate" questions appeared in the first 10-15 suggestions. Instead, StackOverflow made WRONG suggestions for irrelevant -false duplicates.
Here is my suggestion:
Instead of marking questions as "duplicate" why not merge them along with the answers in one single question with an intuitive title?
Thanks for the answers.
UPDATE #2: This is NOT a duplicate. The suggested questions have answers that only refer to OR optimization while my question is more general, it refers to "logic expressions", NOT specifically to OR. I just provided an OR example. I'm specifically asking whether there is a method to avoid repeating the main variable in a logical statement whether it is OR, AND, etc.
For example: given var1 == var2 == var3
if (ext === var1 && ext === var2 && ext === var3 ){
//do something
}
var ext = "_00";
if (/^_st$|^_mt$|^_00$/.test(ext) ){
console.log("do something");
//do something
}
Using regex this is possible.
Explanation:
Each comparison is separated by an |(or) and enclosed in ^ and $ to match exactly otherwise it would match else where.
let ext = "_mt";
if( ext.match( /_st|_mt|_00/g ) ) {
console.log("Yes : type 1");
}
if( ["_st", "_mt", "_00"].includes( ext ) ) {
console.log("Yes : type 2");
}
As #Shily said you can use an array and this kind of regex too

Usefulness of the comma operator in comparisons [duplicate]

This question already has answers here:
When is the comma operator useful?
(15 answers)
Closed 5 years ago.
I saw a comparison like the following in a question on SO:
(pNum != ('2','3','4','5','6','7','8','9'))
The OP has been trying to check if a number falls in a certain range but this code is inaccurate as it will always compare with right most value inside the brace(i.e. 9)
This means when pNum = 2 the comparison will return true and not false as was expected by OP who was expecting it to work like inArray or in.
My question is whether this sort of comparison is going to be useful in any real case in any scenario?
My question is whether this sort of comparison is going to be useful in any real case in any scenario?
No. As you observe, the comparison only compares the last item inside the bracket. So all it can accomplish is to confuse the reader.
If you intend to compare a variable with a set of values, you could use array#includes or array#indexOf >= 0. Something like:
console.log(['2','3','4','5','6','7','8','9'].includes('2'));
console.log(['2','3','4','5','6','7','8','9'].includes('6'));
console.log(['2','3','4','5','6','7','8','9'].includes('9'));
// IE
console.log(['2','3','4','5','6','7','8','9'].indexOf('2') >= 0);
console.log(['2','3','4','5','6','7','8','9'].indexOf('6') >= 0);
console.log(['2','3','4','5','6','7','8','9'].indexOf('9') >= 0);

What is the Javascript equivalent of writing 'If not" [duplicate]

This question already has answers here:
Best way to find if an item is in a JavaScript array? [duplicate]
(8 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Python programmer here.
I don't know how to write this. I tried using 'if !in' and '!if in', but I don't know how. Tried to Google it but got no results.
The correct syntax is
if(!condition){
expression();
}
Note that you need parenthesis around the condition.
#plalx wants a formal definition, and here you go:
IfStatement:
if(Expression) Statement else Statement
if(Expression) Statement
In case of any ambiguity the else would be matched with the nearest if.
If you have some value:
var excludeMe = "something unwanted";
Then you can use the following if statement:
if(myTestCase !== excludeMe) { //do something...}
Keep in mind that != does not check type and !== does check type. So, 1 != "1" is false and 1 !== "1" is true.

Is it better to call if statement or constantly reassign value? (javascript or any language) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Changing the value of a variable to what it might already be
Which is better:
if(value != 1){
value = 1
}
or
value = 1
(This is for a function that is in an animation loop, so its constantly being called, don't know if this is important or not, but thought that I should include that info...)
This is remarkably similar to a story on Computer Stupidities:
I ran across this gem while debugging someone else's old code once:
if (value == 0)
return value;
else
return 0;
In your code, regardless of the original value of value, it will always be 1 by the end. So just set it that way.

Categories