How can I rewrite this conditional statement to be shorter? - javascript

I have a conditional statement with an && and || clause but I would like to shorten and clean this up. Would the best course of action be to rewrite this inside of an array? Should I also turn this into a ternary operator?
Thanks for your help
if ((V1_CCLS == "S06") && ((V1_CCCT === "") || (VS_SELQ == "LED_COUNT_CRNR"))) {
V1_CCCT = V1_CCLS;
}

It would be easier to read if you put it into a variable or function and name is something descriptive so whoever is reading it knows quickly what is going on.
Also, you want to use parentheses with the same rules as algebra. Putting parentheses around (V1_CCLS == "S06") isn't needed, for instance.
For example:
let isReady = V1_CCLS === "S06" && (V1_CCCT === "" || VS_SELQ === "LED_COUNT_CRNR");
if (isReady) {
V1_CCCT = V1_CCLS;
}

I wouldn't use a ternary for this case. I'd just make it a bit more readable by displaying the conditions on separate lines.
if (
V1_CCLS == "S06" &&
(
V1_CCCT === "" ||
VS_SELQ == "LED_COUNT_CRNR"
)
) V1_CCCT = V1_CCLS;

V1_CCCT = (V1_CCLS == "S06") && (!V1_CCCT) || (VS_SELQ == "LED_COUNT_CRNR")) ? V1_CCLS : ""

Related

What's the logic behind the && (and) working while || (or ) doesn't in this code

var answer = prompt("are we there yet")
while(answer.indexOf("yes") === -1 && answer.indexOf("yeah") === -1 ){
var answer = prompt("are we there yet")
}
alert("yay we made it");
&& works when both parts are true, in this case, if we write yes OR yeah it will work, if we write only yes while it works, it's "false" because we didn't write yes AND yeah in the same prompt.
Well obviously i'm wrong. Why doesn't OR work when one of them just needs to be true, I would only need to write either yes or yeah for it to work.
The logic there is little wrong, when you write while statement
while(answer.indexOf("yes") === -1 && answer.indexOf("yeah") === -1 )
here while executes it's body when conditional inside is true
while(*true*) => do something
when you type for example yes in prompt, while takes false as conditional because
(true && false) => false
that means while doesn't execute it's body any more.
when you write || instead of &&
(true || false) => true so while statement continues to execute body
So the write code would be
while(answer.indexOf("yes") !== -1 || answer.indexOf("yeah") !== -1)

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

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.

What is the "angular" way to perform a conditional ng-if check?

Say I have a string that contains a value of "HOMEPAGE"
vm.string = "HOMEPAGE"
and I want to perform an ng-if inside of a div that causes it to display if vm.string is equal to one of these five strings.
"HOMEPAGE"
"ABOUT"
"STORE"
"EXAMPLE"
"SOMETHING"
I could do this using or operators inside of the ng-if to achieve the desired effect
<div ng-if="WhateverController.string == 'HOMEPAGE'
|| WhateverController.string == 'ABOUT'
|| WhateverController.string == 'STORE'
|| WhateverController.string == 'EXAMPLE'
|| WhateverController.string == 'SOMETHING'">
This will display because the string is 'HOMEPAGE'
</div>
I could also do this by creating a function that returns a boolean in my controller.
vm.isTrue = function () {
return (vm.string == 'HOMEPAGE'
|| vm.string == 'ABOUT'
|| vm.string == 'STORE'
|| vm.string == 'EXAMPLE'
|| vm.string == 'SOMETHING');
};
<div ng-if="WhateverController.isTrue">
This will display because the string is 'HOMEPAGE'
</div>
My question to you all is which of these two methods is considered the more "angular" way? I'm partial to doing this inside of the javascript because it makes the HTML look cleaner, but I am curious as to whether there is one way preferred over the other and why.
If you are going to use this check in only one place of your code, i'd say it doesn't matter except if you want your HTML to look cleaner. It's just a matter of preference.
Using a function on the other hand is better if you are going to check that condition several times in your code.
I think second one is better. It's not even Angular way, but way of writing clean code.
You should also avoid writing very long logical conditions and instead split it to several variabled. For example:
vm.age > 5 && vm.age < 100 && vm.name.length > 5 && (vm.location == "Spain" || vm.location == 'England')
You should instead use:
vm.isTrue = function(){
var isOldEnough = vm.age > 5;
var isYoungEnough = vm.age < 100;
var nameLengthIsCorrect = vm.name.length > 5;
var inSpainOrInEngland = ["Spain","England"].includes(vm.location);
return isOldEnough && isYoungEnough && nameLengthIsCorrect && inSpainOrEngland;
}
This way your code is self-explanatory.

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

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