This question already has answers here:
Check variable equality against a list of values
(16 answers)
Closed 5 years ago.
I feel like I come across this a lot and that intuitively, there should be a way to do something like this:
if (userType ==="admin" || userType === "superUser"){
// do stuff
}
In a more elegant way, like this:
if (userType === ("admin" || "superUser")){
// do stuff
}
Obviously that^ doesn't work because if the first value resolves to true, it will never check if it's the second ("superuser").
Is there shorthand to do this in a JS if-statement where you wouldn't have to repeat the variable name?
Switch statements don't count! ;D
JavaScript doesn't provide out of the box such a syntax.
Now, you can do something of close enough with the Array.includes() method.
It returns true if the element is found in the array.
Otherwise if returns false.
var userTypes = ["admin", "superUser"];
if (userTypes.includes(userType)){
// do stuff
}
or by inlining the array value :
if (["admin", "superUser"].includes(userType)){
// do stuff
}
you can use an array with indexOf. something like
if(["superUser", "admin"].indexOf(userType) >= 0){
//code goes here
}
You could use an object for fast checking.
if ({ admin: 1, superUser: 1 }[userType]) {
// do something if true
}
Related
Example:
When I check a variable containing this value [""] it returns false.
var th=[]
th.push("");
if($("#multiselect").val()==th)
It returns always false.
Thank you.
Edit 1:
changed Var to var. It was a typo.
Edit 2:
Actually, the problem I faced was I was trying to get the value from a multi-select input. The multi-select input sometimes returns values as [""] even I haven't selected any values basically it's a plugin. So I was confused and I thought [""] is a fixed primitive value like 1, 10, "bla blah",.. So I tried to compare it with the same array as the right-hand side of the '=' operator.
It was stupid. Now I posted the solution to my problem and I explained my stupidity.
there are two things:
Change Var to var
You can use includes method of Array as:
var th = [] <==== chnage Var to var
th.push("");
if(th.includes($("#multiselect").val())) { <=== you can use includes method of array
// DO whatever you want
}
Make sure var is lowercased.
You are accessing th as an array, so you’ll need to specify the index of the value you are checking: th[0]
Use triple equals, too: .val()===th[0]
Double check the jquery docs if you’re still running into trouble.
Happy coding!
A couple of things to consider:
You have a typo in the code above; var is valid; Var is invalid.
Browser will aptly complain to solve this typo.
You are comparing an array to DOM value; this will always be false.
DOM is a costly process. Unless the value associated is dynamic, its better to read once, store value into a variable and continue processing instead of reading from DOM always.
You could choose to try something on these lines:
let arr = [1,2,3,4];
let domValue = $("#multiselect").val();
arr.push(5);
arr.map((el, ix) => {
if el === domValue return true; //or choose to do something else here.
});
var th=[]; //It is var not Var
th.push("");
if($("#multiselect").val()==th[0]) // change th to th[0]
I am unable to comment so having to use an answer for now. Are you trying to check if an array has any values? If so you can use
if(th.length){
// do something
}
If you want to check a normal variable for empty string you can simply use
if(th == “”){
//do something
}
I found the solution after a couple of days when I posted this question. Now I can feel how stupid this question was.
Anyway, I'm answering this question so it might help others.
Answer to my question:
When two non-primitive datatype objects(which is the Array here) are compared using an assignment operator, it compares its reference of the object. So the object creation of both arrays would be different. If I want to check the array has [""] value, I should do something like the below.
function isArrValEmptyCheck(value) {
return !value || !(value instanceof Array) || value.length == 0 || value.length == 1 && value[0] == '';
}
console.log(isArrValEmptyCheck([""]));//returns true
console.log(isArrValEmptyCheck(["value1"]));//returns false
Sorry for the late response. Thanks to everyone who tried to help me.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript: The prettiest way to compare one value against multiple values
Javascript If statement used to check file extensions not working
In JS I'm trying to check whether an extension ends in "png" "jpg" or "gif". I'm aware this can be done with a switch statement, but I'm wondering if there's a simpler way to throw it all in the if conditional. Like:
if (aExtensions[i].toLowerCase() == ('jpg' || 'png' || 'gif')) {}
What's the best way to achieve this?
You could use an array like this:
var extensions = ["jpg", "png", "gif"];
if (extensions.indexOf(aExtensions[i].toLowerCase()) > -1) {
// match
}
In this case, you store the "valid" extensions. Then, you can use the indexOf method of Array to find if any of the items in the array match the specific extension you're looking at - checking for a value that is 0 or greater.
indexOf isn't supported on older browsers, so you'd need to include a polyfill to back it up. There are several solutions for that.
Of course, if you wanted to only use if statements, you could use this format:
var ext = aExtensions[i].toLowerCase();
if (ext == "jpg" || ext == "png" || ext == "gif") {
// match
}
Another possibility I can think of is a switch statement, like:
var ext = aExtensions[i].toLowerCase();
switch (ext) {
case "jpg":
case "png":
case "gif":
// match
break;
case default:
// No match
}
I might as well include it (other answers had it first, definitely), but one more I can think of is using a regex, like:
if (/jpg|png|gif/i.test(aExtensions[i])) {
// match
}
But note that you will never be able to individually get the extensions back, and that's why I would prefer one of the first two options I gave.
What about a regex?
if ( /jpg|png|gif/i.test( aExtensions[i] ) ) {
...
}
Yet another way to do this is by using an object literal like this,
if ({'jpg':1,'png':1,'gif':1}[aExtensions[i].toLowerCase()]) {
// ...
}
This way you're looking to see if the anonymous object {'jpg':1,'png':1,'gif':1} has a property which will be true by the if. 1 meets this, undefined doesn't.
If you're using an object, you could also make use of the in operator (as pointed out by Ian) which gives true if the object has such a key irrelevant of it's value.
if (aExtensions[i].toLowerCase() in {'jpg':0,'png':1,'gif':2}) {
// ...
}
Note this time how 'jpg' still passes even though 'jpg':0.
You could use a variable and triple comparison, but that's ugly.
Or you could just use an array and check if the string is contained in it.
if (~ ["jpg", "png", "gif"].indexOf(aExtensions[i].toLowerCase()) …
Yet, for the complicated != -1 comparison and the lack of native indexOf in older IEs, people tend to use regexes:
if (/jpg|png|gif/i.test(aExtensions[i])) …
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;
This question already has answers here:
Cannot set boolean values in LocalStorage?
(10 answers)
Closed 2 years ago.
I want this code to find a local storage value and if it is true show a grid but if it is false, hide the grid. I tried this code but I can't get it to work right. Any ideas on what I did wrong?
var v = localStorage.getItem('checkcalfid');
if (v===true)
{
jQuery('[name="mobilegridcell_385"]').closest("tr").show();
}
else jQuery('[name="mobilegridcell_385"]').closest("tr").hide();
Try JSON.parse it could be that the value stored is not a boolean and make sure you use JSON.stringify when you set the item.
// storing value using JSON.stringify
localStorage.getItem("key",JSON.stringify(value));
-------------------------------------------------------------
// retrieving value using JSON.parse
var v = JSON.parse(localStorage.getItem('checkcalfid'));
if (v===true)
{
jQuery('[name="mobilegridcell_385"]').closest("tr").show();
}
else jQuery('[name="mobilegridcell_385"]').closest("tr").hide();
The getItem function of localStorage return string if you want your code to work consider change it to.
Here is a jsfiddle example : https://jsfiddle.net/dkabf953/1/
var v = localStorage.getItem('checkcalfid');
if (v== 'true') { // Check if it's equal to the string true
jQuery('[name="mobilegridcell_385"]').closest("tr").show();
} else {
jQuery('[name="mobilegridcell_385"]').closest("tr").hide();
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript: The prettiest way to compare one value against multiple values
Javascript If statement used to check file extensions not working
In JS I'm trying to check whether an extension ends in "png" "jpg" or "gif". I'm aware this can be done with a switch statement, but I'm wondering if there's a simpler way to throw it all in the if conditional. Like:
if (aExtensions[i].toLowerCase() == ('jpg' || 'png' || 'gif')) {}
What's the best way to achieve this?
You could use an array like this:
var extensions = ["jpg", "png", "gif"];
if (extensions.indexOf(aExtensions[i].toLowerCase()) > -1) {
// match
}
In this case, you store the "valid" extensions. Then, you can use the indexOf method of Array to find if any of the items in the array match the specific extension you're looking at - checking for a value that is 0 or greater.
indexOf isn't supported on older browsers, so you'd need to include a polyfill to back it up. There are several solutions for that.
Of course, if you wanted to only use if statements, you could use this format:
var ext = aExtensions[i].toLowerCase();
if (ext == "jpg" || ext == "png" || ext == "gif") {
// match
}
Another possibility I can think of is a switch statement, like:
var ext = aExtensions[i].toLowerCase();
switch (ext) {
case "jpg":
case "png":
case "gif":
// match
break;
case default:
// No match
}
I might as well include it (other answers had it first, definitely), but one more I can think of is using a regex, like:
if (/jpg|png|gif/i.test(aExtensions[i])) {
// match
}
But note that you will never be able to individually get the extensions back, and that's why I would prefer one of the first two options I gave.
What about a regex?
if ( /jpg|png|gif/i.test( aExtensions[i] ) ) {
...
}
Yet another way to do this is by using an object literal like this,
if ({'jpg':1,'png':1,'gif':1}[aExtensions[i].toLowerCase()]) {
// ...
}
This way you're looking to see if the anonymous object {'jpg':1,'png':1,'gif':1} has a property which will be true by the if. 1 meets this, undefined doesn't.
If you're using an object, you could also make use of the in operator (as pointed out by Ian) which gives true if the object has such a key irrelevant of it's value.
if (aExtensions[i].toLowerCase() in {'jpg':0,'png':1,'gif':2}) {
// ...
}
Note this time how 'jpg' still passes even though 'jpg':0.
You could use a variable and triple comparison, but that's ugly.
Or you could just use an array and check if the string is contained in it.
if (~ ["jpg", "png", "gif"].indexOf(aExtensions[i].toLowerCase()) …
Yet, for the complicated != -1 comparison and the lack of native indexOf in older IEs, people tend to use regexes:
if (/jpg|png|gif/i.test(aExtensions[i])) …