Can you have multiple and operators in JavaScript? - javascript

I have the following code:
if ((showHideDropdown.target.id !== "gear-icon") && (showHideDropdown.target.id !== "gear-image") && (showHideDropdown.target.id !== "settings") && (showHideDropdown.target.id !== "profile-icon") && (showHideDropdown.target.id !== "profile-image")){
I always thought that multiple and operators can be used like this, but nothing after the first two target id's worked. Maybe this has nothing to do with the operators, which is why I am asking if you can have multiple operators in a line. I'm a beginner in js so I haven't met this kind of problem before.

You can have multiple && conditions, but you'd probably be better off simplifying your check since your conditions seem to have lots of repetition of the same field. For instance:
const id = showHideDropdown.target.id;
const list = [`gear-icon`, `gear-image`, `settings`, `profile-icon`, `profile-image`];
if (!list.includes(id)) {
//...
}

Related

JS making a forEach match more efficient

variants is an object of objects and selectedOptions is an object of option1, option2, option3. The below forEach searches through the variants to find a match.
Is there a more efficient way, using an array method or similar, to do the following:
Object.values(variants).forEach(variant => {
if (variant.options.option1 === selectedOptions.option1 && variant.options.option2 === selectedOptions.option2 && variant.options.option3 === selectedOptions.option3) {
selectedVariant = variant.gid;
}
});
One thing you're doing here is loop through all the variants, overwriting selectedVariant each time you find a match. And if there's supposed to be only one match, you still visit all the other variants when there's no need for it anymore.
More efficient would be:
selectedVariant = Object.values(variants).find(variant => (
variant.options.option1 === selectedOptions.option1 &&
variant.options.option2 === selectedOptions.option2 &&
variant.options.option3 === selectedOptions.option3
)).gid;
That way you stop the moment you find a match.
And to be perfectly honest, setting a variant equal to another variant's gid looks wrong. Either name the variable you assign to selectedVariantGid, or assign the entire variant, and later use the .gid property once you need it. Clear naming is important.

How to check if user's ID is the same and act on the result?

Vague question, but my discord bot includes a !kick command, but I'm looking to give myself and others immunity by checking if the kick target has a specific ID tied to their user. I've checked if it's not able to read ID, and it's successfully returned the target's ID before, so I've eliminated the problem to the section where it compares ID's.
enter code hereCode: https://pastebin.com/uFbgzXXv
One issue I see with your code is your if statements. Multiple times you do something like this inside an if statement:
if( message.mentions.users.id === "155478460620341248" || "121733886278500354" || "138121422865301505")
return message.channel.send("JAKE AND YUNUS ARE IMMUNE!")
When checking if a specific value (like message.mentions.users.id) is equal to multiple different strings, you have to do multiple message.mentions.users.id === "<user id>" statements like this:
if( message.mentions.users.id === "155478460620341248" ||
message.mentions.users.id === "121733886278500354" ||
message.mentions.users.id === "138121422865301505" )
return message.channel.send("JAKE AND YUNUS ARE IMMUNE!");
You can even make this a bit nicer by doing something like this:
let skipUsers = [ "155478460620341248", "121733886278500354", "138121422865301505" ];
if ( skipUsers.includes(message.mentions.users.id) )
return message.channel.send("JAKE AND YUNUS ARE IMMUNE!");

shorten javascript code - check if property exists and is not empty [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 6 years ago.
Is it possible to shorten this code?
var access_followup = user_access && user_access.followup && user_access.followup.access ? true : false;
Unfortunately JS does not have a null conditional operator. You could write helper function for it or use a slightly less effective method of creating dummy objects:
var access_followup = !!((user_access || {}).followup || {}).access;
which is shorter and prevents using the property names more than once, but doesn't improve readability. The !! is used to enforce a boolean value even when the values don't exist
Maybe I am answering the wrong thing, but why would you want to make it shorter? I'd vote to make it a bit longer, but easier to read for people who work with your code ( including you :) ).
You could make it more readable by splitting it up into multiple lines:
var access_followup = (
user_access &&
user_access.followup &&
user_access.followup.access === true // if access is a boolean value
);
Or, in case you really really want to have short code and you do not use a minifier already, you can try https://jscompress.com/ (which actually compresses any code you paste into it! but makes it WAY less readable).
If the first 2 checks are because you are protecting against exception thrown when user_access.followup is undefined, you can try this:
var accessFollowup;
try {
accessFollowup = !!user_access.followup.access;
} catch (e) {
accessFollowup = false;
}
You could also shorten by removing just the ternary by using !! to force last element into Boolean value:
var access_followup = !!user_access && !!user_access.followup && !!user_access.followup.access
very ugly code that works
var access_followup = (followup = (user_access || {}).followup) && followup.access;

&& / || operator strangeness in JavaScript

So, I was working on a project of mine, when I came across a problem like this:
var one = 1;
var two = 2;
var three = 7;
if (one === 1 || two === 2 && three === 3) {
console.log("ok"); // prints out ok
}
I'm pretty confused with this since I don't think it should print out "ok". I thought that since the condition after the && operator was false, it shouldn't run, but I'm evidently wrong. Can anyone clarify why it's working?
In Javascript, operators are not just evaluated left-to-right, certain operators have more precedence than others. Those with higher precedence (in this case, the && operator of precedence 13) will be evaluated before others (||, precedence 14).
For your particular case, you need to group your conditionals in order to achieve the functionality you want:
if ((one === 1 || two === 2) && three === 3) {
console.log("ok"); // prints out ok
}
JSFiddle

Javascript only checks one field

Ok so I've been stumped on this one for days and its frustrating me. (Will frustrate me even more if it's something simple I'm overlooking).
I have a form generated in PHP which I want to verify that certain pieces are filled out. I do this via a JavaScript check when the user clicks the submit button.The JavaScript code is below:
<script language="JavaScript">
function checkFields()
{
if (document.getElementById('ldescription').value == '' || document.getElementById('uname').value == ''
|| document.getElementById('sdescription').value == '' || document.getElementById('email').value == ''
|| document.getElementById('platf').value == "Select Group" || document.getElementByID('cate').value == "Select Category" )
{
alert("Please fill out all of the starred (*) items" );
return false;
}
}
</script>
For some reason though this only checks the ldescription field. If that field has text but all the others are empty it carries on like everything was filled out. Also if I change the order of my checks and ldescription is anywhere but the first check, it will do no check whatsoever even when all the fields are empty.
Any ideas?
EDIT:
Got it fixed. Along with the suggestion I marked as correct the document.getElementById('item').value command worked with only textarea boxes but not regular text input boxes. By changing the command to document.MyForm.myTextName.value everything fell into place.
Couple of problems i noticed with your sample code.
The last getElementById call has improper casing. The final d is capitalized and it shouldn't be
Comparing the value to a string literal should be done by === not ==.
JSLint complains there are line break issues in your if statement by having the line begin with || instead of having the previous line end with ||.
The first and third items are most likely the ones causing your problem.
Inside your if condition, when you are breaking a line, make sure that the last token in the line is the OR operator ||.
Javascript does semicolon insertion, so it may be that semicolons are being inserted (automatically, invisibly, by the interpreter) in a bad place.
Try the below code
<script language="JavaScript">
function checkFields()
{
if (document.getElementById('ldescription').value === '' ||
document.getElementById('uname').value === '' ||
document.getElementById('sdescription').value === '' ||
document.getElementById('email').value === '' ||
document.getElementById('platf').value === "Select Group" ||
document.getElementById('cate').value === "Select Category")
{
alert("Please fill out all of the starred (*) items" );
return false;
}
}
</script>
Please use Javascript && operator which returns true if both the elements are true. || operator evaluates to true in case atleast one of the element is true which is what is happening in your case. You can take a look at Javascript boolean Logic

Categories

Resources