using if statement with && and || inside for loop - javascript

I have an if statement inside for loop with more than one condition. I want to match the data in database with input data in an HTML form. When the input field in the form is blank it is stored as null in the database. I have this column(itemsSortedByDate[i].FD_MIMO) in the database which can be null or can have some value. I am unable to match the blank field with null in the database. Also even if that column(itemsSortedByDate[i].FD_MIMO) has some value in the database, my for loop searches for the database which has null field just because other fields are matching. My Javascript is as below. The last condition is creating problems. ScenarioListViewModel.fdMimo()and itemsSortedByDate[i].FD_MIMO are supposed to be same whether it's null or has some value. But in the console.log they are different. Thank you for your help, much appreciated.
self.getJobIdForCapacity = function(itemsSortedByDate){
var jobIdForCapacity;
var found = false;
for (var i = 0, len = itemsSortedByDate.length; i < len; i++) {
if(itemsSortedByDate[i].DB_Name == ScenarioListViewModel.db_name()
&& itemsSortedByDate[i].Split_Mode == ScenarioListViewModel.splitMode()
&& itemsSortedByDate[i].Full_Output == ScenarioListViewModel.fullOutput()
&& (itemsSortedByDate[i].Workflow_Status == "Completed" || itemsSortedByDate[i].Workflow_Status == "Running")
&& (itemsSortedByDate[i].Disposition == "Success" || itemsSortedByDate[i].Disposition == "None")
&& (itemsSortedByDate[i].FD_MIMO == ScenarioListViewModel.fdMimo() || itemsSortedByDate[i].FD_MIMO == null)){
jobIdForCapacity = itemsSortedByDate[i].Title;
console.log("Job Id:" + jobIdForCapacity);
console.log("fdmimo from form:" +ScenarioListViewModel.fdMimo());
console.log("fdmimo from list:" +itemsSortedByDate[i].FD_MIMO);
self.getJobResults(jobIdForCapacity);
found = true;
break;
}
}
if (!found) {
alert("Job not found in Sharepoint Execution History List. Click Execute Model to run");
}
};

I would suggest you use === in all the conditions in if statement and it may help you solve your problem as there is difference in === vs ==.
Please refer this question for the difference.
For example:
itemsSortedByDate[i].DB_Name == ScenarioListViewModel.db_name()
will be
itemsSortedByDate[i].DB_Name === ScenarioListViewModel.db_name()
Condition:
"Completed" || itemsSortedByDate[i].Workflow_Status == "Running"
will always return "Completed" does not matter itemsSortedByDate[i].Workflow_Status == "Running" is true or false. Here your can use ternary operator like
itemsSortedByDate[i].Workflow_Status == "Running"? "Running" : "Compelted"
Something of this kind. Check all conditions like this.

Related

With an If statement, how can I skip a variable being checked if its property could be undefined?

I would like to be able to skip checking a variable if the property (.emailAddress) has the chance of being undefined but continue checking the others.
For example, I'm checking an entered email address if its an existing contact (email) on the page.
if(inputEmail.length > 0 && inputEmail.indexOf('#') > 0 */ check that the input is not blank & is probably an email address.
&& inputEmail !== existingContact1.emailAddress
&& inputEmail !== existingContact2.emailAddress
&& inputEmail !== existingContact3.emailAddress
&& inputEmail !== existingContact3.emailAddress
) {
// execute code
}
My problem occurs if .emailAddress is undefined, as you can't check undefined in an If statement.
.emailAddress could be any combination of existingContact 1-4 that could be undefined or not.
can’t check should read can’t compare undefined.
I've tried using typeof to find if it is undeclared with not the results I was expecting.
&& typeof existingContact1 == "undefined" || typeof existingContact1.emailAddress == "undefined" && existingContact1.emailAddress !== inputEmail
What are some diffrent approaches to be able to anticpte and skip over if .emailAddress has the chance of being undefined?
In programming undefined & null evaluate/return to false, so check like this
if(inputEmail && inputEmail.indexOf('#') > 0 */ check that the input is not blank & is probably an email address.
&& inputEmail !== existingContact1.emailAddress
&& inputEmail !== existingContact2.emailAddress
&& inputEmail !== existingContact3.emailAddress
&& inputEmail !== existingContact3.emailAddress
) {
// execute code
}
try the approach like
var existingContact1 = { emailAddress: 'abc#zyz.com' }
var existingContact2 = { emailAddress: 'abc#zyz.com' }
var existingContact3 = { emailAddress: 'abc#zyz.com' }
var existingContact4 = { emailAddress: 'abc#zyz.com' }
if(inputEmail.length > 0 && inputEmail.indexOf('#') > 0 */ check that the input is not blank & is probably an email address.
&& [existingContact1, existingContact2, existingContact3, existingContact4]
.map(({ emailAddress }) => emailAddress) // get existing emails
.filter(x => x) // remove falsy values if any
.indexOf(inputEmail) > -1 // check if available
) {
// execute code
}
The wonderful thing about javascript is you can work with undefined. I highly recommend keeping everything as simple as possible at all times. Let's cover some cases:
You can literally assess with === operator if something is undefined. === returns true when the values on both sides are equal in value and type, which is how you'd check if a value is not defined in the most explicit way.
You can use a lazy falsy check, which is actually what I recommend. Using !!x (or just x in an If statement) will coerce it to boolean, and it will return true if x is a non-empty string and is not undefined.
I want to add as a footnote that I would recommend just keeping an array called emailsOnPage and then checking if input.email is in the array, rather than manually checking 4 conditions.
Robin mentioned the case insensivity of emails, and that's easy to do; just use the form if(x.toLowerCase() == y.toLowerCase()).

Passing condition to a var in javascript

I don't know how to solve this. I need something like this:
var condition;
if (a==1) //a comes from another part
condition = "arr3[cliente].año == year";
if (a==2)
condition = "arr3[cliente].año == year && arr3[cliente].sic"
//now another if
if (condition){
//rest of code
}
I need different conditions depending some previous values, the code inside the last if is always the same, so I don't need:
if (arr3[cliente].año == year)
// code
else if (arr3[cliente].año == year && arr3[cliente].sic)
// code
How can I do it?
Just assign the result of the expressions to the variable (currently you are assigning a string). The expression doesn't have to be inside the if statement, the result is what's important:
var condition;
if (a==1)
condition = arr3[cliente].año == year;
if (a==2)
condition = arr3[cliente].año == year && arr3[cliente].sic;
// It this point `condition` will either have the value `undefined`, `true` or `false`.
if (condition) {
// code
}
Of course you can simplify/reduce this to the following:
if (arr3[cliente].año == year && (a == 1 || a == 2 && arr3[cliente].sic)) {
// code
}
No need for repeating if statements or comparisons. This also assumes that accessing any of the properties doesn't have any side effects.
Just use the conditions you have, but not as strings. They'll either be true or false and your if(condition) check will still work fine.
var condition;
if (a == 1) //a comes from another part
condition = arr3[cliente].año == year;
if (a == 2)
condition = arr3[cliente].año == year && arr3[cliente].sic;
//now another if
if (condition) {
//rest of code
}
My proposition. if a==1 you will need the rest of condition and if a==2 you'll need second option condition.
if (a==1 && (arr3[cliente].año == year)){
commonFunction();
} else if (a==2 && (arr3[cliente].año == year && arr3[cliente].sic)){
commonFunction();
}
function commonFunction() {
//rest of code
}

Does Javascript have a way to simplify multiple checks for a value to be one of?

I have this code:
if (tes.test.userTestStatusId != UserTestStatus.MarkedByAdmin &&
tes.test.userTestStatusId != UserTestStatus.MarkedByUser &&
tes.test.userTestStatusId != UserTestStatus.Paused &&
tes.test.userTestStatusId != UserTestStatus.Completed) {
Is there some way I could simplify this so as not to repeat "tes.test.userTestStatusId" each time?
If strict equality is OK, you can store the values as an array and use indexOf:
var statuses = [UserTestStatus.MarkedByAdmin, ...];
if (statuses.indexOf(userStatusId) === -1) {
//...
}
you can cache the value
var userId = tes.test.userTestStatusId;
if (userId != UserTestStatus.MarkedByAdmin &&
userId != UserTestStatus.MarkedByUser &&
userId != UserTestStatus.Paused &&
userId != UserTestStatus.Completed)
{
put the status in an array
var statuses = [ UserTestStatus.MarkedByAdmin, UserTestStatus.MarkedByUser, UserTestStatus.Paused, UserTestStatus.Completed];
now check the index
if ( statuses.indexOf( userId ) == -1 )
This won't be much less code, but it will be much more stable — you'll be able to add/remove cases from the status object without having to change the code.
The idea is to iterate through UserTestStatus properties and look for any that match:
if (!Object.keys(UserTestStatus).some(function(key) {
return UserTestStatus[key] == test.test.userTestStatusId;
})) {
// no matches found
}
Now if you come back and add a new case (maybe UserTestStatus.Failed or UserTestStatus.NotStarted) that code won't have to change.
You can use Array.some():
if (![
'MarkedByAdmin',
'MarkedByUser',
'Paused',
'Completed'
].some((p) => UserTestStatus[p] === tes.test.userTestStatusId)) {
// ...
}
But I personally think that the vanilla conditional approach is cleaner.
If I understand your question correctly, you can save the id in a new var and then use it in the if condition like below:
var statusId=tes.test.userTestStatusId;
if ( statusId!= UserTestStatus.MarkedByAdmin &&
statusId != UserTestStatus.MarkedByUser &&
statusId != UserTestStatus.Paused &&
statusId != UserTestStatus.Completed) {
But if you are looking for the way to combine multiple logical check in a single usage, it will not be effective as far as I know

"If" consolidation/avoiding nesting

I'm really trying to avoid nesting in this code snippet...
deal_trade_in_model_1 = document.getElementById('deal_trade_in_model_1').value;
deal_trade_in_amount_1 = document.getElementById('deal_trade_in_amount_1').value;
if (typeof deal_trade_in_model_1 !== 'undefined' && deal_trade_in_model_1 !== null) {
console.log(deal_trade_in_amount_1);
console.log(deal_trade_in_model_1);
if (deal_trade_in_model_1 !== null || deal_trade_in_model_1 !== "") {
if (deal_trade_in_amount_1 == null || deal_trade_in_amount_1 == "") {
console.log('entered into function');
document.getElementById("deal_trade_in_model_1").value = "";
document.getElementById("deal_trade_in_amount_1").value = "";
}
}
}
Basically, what this function does is take the value of two fields... things to know about them and what I want to do to them:
1) They're NOT required
2) If one of them is filled out, the other must be
3) If ONLY one of them is filled out, the user clicks submit, and this part of the function is called upon, I want to delete the value of both of them.
I've tried doing a compound of
&& (and)
and
|| (or)
buttttt it odiously it didn't work.
Primary question: What's the best way to get rid of the nesting (I planned on doing this twice and just swapping the code) that will be the most efficient? This, I want, to be done preferably in the smallest amount of IF statements possible.
Please note: If you change the code a lot, I might not know what you're talking about.. please be prepared to teach me or help me learn!
It sounds like you only want to do something if either of the fields are empty, but not both. Assuming both of the elements are text fields, .value will always return a string. Converting a string to boolean results in false if the string is empty, otherwise true.
So
Boolean(deal_trade_in_model_1) === Boolean(deal_trade_in_amount_1)
will be true if either both fields have a value (both will convert to true) or both fields are empty (both convert to false).
Thus your code can be reduced to
var model_1 = document.getElementById('deal_trade_in_model_1');
var amount_1 = document.getElementById('deal_trade_in_amount_1');
if (Boolean(model_1.value) !== Boolean(amount_1.value)) {
model_1.value = "";
amount_1.value = "";
}

How do you make a javascript "if" statement with both "and" and "or"?

I'm trying to make a page where you fill in some input boxes and check a radio button, and if you complete all of it, you can click a div, and animations happen. The specific input boxes are not the only ones on the page. I'm trying to use a javascript "if" statement that has a bunch of "and"'s and an "or" in parentheses, but when I open the page, the code doesn't run. This isn't all my code, and I know the javascript and it's libraries are linked because I've been coding this site for a while, and everything has worked up until now. I checked the code in a javascript validator and it seemed fine. I'm not sure what I'm doing wrong.
$(document).ready(function(){
if ( $(".managementCompanyName").val() !== '' &&
$(".approvedBy").val() !== '' &&
$(".contractStartDate").val() !== '' &&
$(".proposalNumber").val() !== '' &&
$(!$("input[name='proposalReviewedForInvoice']:checked").val() || !$("input[id='proposalNotReviewedForInvoice']:checked").val()) ) {
//do stuff
}
});
Alternatively I have
$(document).ready(function(){
if ( $(".managementCompanyName").val() !== "" &&
$(".approvedBy").val() !== "" &&
$(".contractStartDate").val() !== "" &&
$(".proposalNumber").val() !== "" &&
$("input[name='proposalReviewedForInvoice']:checked").val() !== "" ) {
//do stuff
}
});
This code seems to work on another part of the site where there's only one input as a requirement.
Thank you if you can spot my error.
Wrap the || part in parentheses, otherwise the first operand to || is actually the last result from the last &&.
/*$*/(!$("input[name='proposalReviewedForInvoice']:checked").val() ||
!$("input[id='proposalNotReviewedForInvoice']:checked").val()) ) {
And actually it seems that you rather had them wrapped in a $(), which will always return a jQuery object, which will always be "truthy" in the condition.
for handling errors much better if you only used the "OR (||) " condition.
$(document).ready(function(){
var management = $(".managementCompanyName").val();
var approved = $(".approvedBy").val();
var contract = $(".contractStartDate").val();
var proposed_num = $(".proposalNumber").val();
var proposed_rev = $("input[name='proposalReviewedForInvoice']:checked").val();
if ( management == '' || approved == '' || contract == '' || proposed_num == ''
|| proposed_rev == '' ) {
// error message
} else {
// do stuff
}
});

Categories