How to combine two value checks into one line in javascript - javascript

I have the following code in javascript:
var seasonDropdown = TVContainer.find('select.season').val()
if (seasonDropdown == "-1" || !seasonDropdown) {seasonDropdown = null}
Is there a way to combine these two into one line?

You could do the following:
var seasonDropdown = (TVContainer.find('select.season').val() == "-1" || !TVContainer.find('select.season').val()) ? null : TVContainer.find('select.season').val();
But honestly, you should prefer readability over a solution like this.
if you want a bit cleaner look instead, you could use this:
var seasonDropdown = TVContainer.find('select.season').val();
if (seasonDropdown == "-1" || !seasonDropdown) seasonDropdown = null;

Related

JavaScript with coffescript syntax- if condition : optimize if statement structure

I have a function and I'm testing 4 variables, I want to optimize the structure of my if statement test, can some one help ? :
$scope.filterActivated = ->
if $scope.postParams.options.scopes.report.from || $scope.postParams.options.scopes.report.to || $scope.postParams.options.template_id || $scope.displayOptions.query.length > 0
return true
else
return false
you can remove true/false and optimize it a little bit like this:
$scope.filterActivated = ->
options = $scope.postParams.options
options.scopes.report.from or options.scopes.report.to or options.template_id or $scope.displayOptions.query.length > 0
Edit: JS for you:
$scope.filterActivated = () => {
let options = $scope.postParams.options;
return options.scopes.report.from || options.scopes.report.to || options.template_id || $scope.displayOptions.query.length > 0;
};
Not sure what you mean by optimizing, but a shorthand of that could be:
$scope.filterActivated = ->
$scope.postParams.options.scopes.report.from
|| $scope.postParams.options.scopes.report.to
|| $scope.postParams.options.template_id
|| $scope.displayOptions.query.length;
Edit:
Initially, I used the ternary syntax, but that's not supported by CoffeeScript. For reference Ternary operation in CoffeeScript
Edit 2:
Reduced it a bit more, #user633183 suggested using Boolean but I think this gives the same result.

JS Ternary functions with multiple conditions?

I have been using a ternary operator in JavaScript to modify the value of an object based on user input. I have the following code, which runs as it should:
var inputOneAns = inputOne == "Yes" ? "517" : "518";
As you can see, I am assigning a numeric string value to inputOneAnswhether a user has inputed "Yes" or "No". However, there may be a case that a user has not selected a value (as it is not required). If this input was left blank, I would like to assign an empty string "" to inputOneAns. Is there a wayf or me to embed an ternary operator inside of another ternary operator? To help clarify, here is the same function that I want to accompolish with my ternary function but with if else statements?
if (inputOne == "Yes"){
var inputOneAns = "517"
}else if (inputOne == "No"{
var inputOneAns = "518"
}else{
var inputOneAns = ""
}
Is it possible to include multiple expressions into a ternary function? Is there a better way to accomplish what I am looking for? Thanks for the tips in advance.
Yes you can go wild nesting ternaries. I find this version to be fairly readable:
var foo = (
bar === 'a' ? 1 : // if
bar === 'b' ? 2 : // else if
bar === 'c' ? 3 : // else if
null // else
);
but that's not a widely shared opinion, and you should probably stick to if/else or switch when working on a team.
Yes, you can use multiple condition in Ternary Operator. Hope this will help you.
var x=20;
var y = x<13 ? "Child" : x<20 ? "Teenage" : x<30 ? "Twenties" : "Old people";
console.log(y);
A switch statement is likely the best choice in a situation like this.
let inputOneAns;
switch(inputOne) {
case "Yes":
inputOneAns = "517";
break;
case "No":
inputOneNas = "518";
break;
default:
inputOneNas = "";
}
If you could do ternary operations beyond 2 conditions, they would become incredibly messy. You can put conditions together, but I've no idea why you would want that - that would be incredibly messy.
The most elegant and clean way is to take advantage of Object literals:
const Switch = (str) => ({
"Yes": "517",
"No": "518",
})[str] || '';
console.log(Switch("Yes")); // 517
console.log(Switch("No")); // 518
console.log(Switch("Non matching value")); // Empty
This has the advantage of being both readable and flexible.
Yeh you can chain them together much like using an else if statement, but it can sometimes be a bit hard to read though, so I tend to split mine over multiple lines.
var inputOneAns = inputOne == 'Yes' ? '517' :
inputOne == 'No' ? '518' : '';
However in this case I would suggest a switch statement seeing as you're comparing the same value for every case.
var r = inputOne == "" ? "" : (
inputOne == "Yes" ? "517" : "518");
Unfortunately JavaScript does not provide a super terse and readable way to do this. Personally I would just use some single-line if statements like this:
var inputOneAns;
if (inputOne === 'Yes') inputOneAns = '517';
if (inputOne === 'No') inputOneAns = '518';
else inputOneAns = '';
Which can be even cleaner if you abstract it into a function (note: no need for else in this case):
function getInputOneAns(inputOne) {
if (inputOne === 'Yes') return '517';
if (inputOne === 'No') return '518';
return '';
}
Personally, I don't really like switch statements for this for two reasons: firstly those extra break statements bloating the code, and secondly, switch statements are very limiting - you can only do simple equality checks, and only against a single variable. Besides, in the case that you know you will be always checking a single string I would favour a simple map object:
var map = { 'Yes': '517', 'No': '518' };
var inputOneAns = map[inputOne] || '';
Yes, and it does provide a cleaner code than switch statement.. with all the breaks..
inputOne == "Yes" ? "517" :
inputOne == "No" ? "518" : inputOneAns = "";
Seems like a classic use for a switch statement:
let inputOneAns = '';
switch(inputOne) {
case 'Yes':
inputOneAns = "517";
break;
case 'No':
inputOneAns = "518";
break;
default:
inputOneAns = "";
}
note you don't actually need the default case, but I find it makes things more readable.

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

JavaScript: Declaring VAR with 'or' statement

the code is something like this
var $page_products = $page_name == 'products-uninterruptible-power-supply.php' OR 'products-uninterruptible-power-supply-np2031.php';
i already tried using
var $page_products = $page_name == 'products-uninterruptible-power-supply.php' || 'products-uninterruptible-power-supply-np2031.php';
but it is still not working. thanks in advance!
Assuming your intention is to declare one variable, $page_products, which will be set to true if the $page_name is equal to either of those two strings and false otherwise, do this:
var $page_products = $page_name == 'products-uninterruptible-power-supply.php'
|| $page_name == 'products-uninterruptible-power-supply-np2031.php';
EDIT: I just noticed that both page names start with the same four words, so instead of comparing to each string it may suit you to test whether the value in $page_name starts with those words, e.g.,:
var $page_products =
$page_name.indexOf('products-uninterruptible-power-supply') === 0;
This should work
var $page_products = ($page_name == 'products-uninterruptible-power-supply.php' || $page_name == 'products-uninterruptible-power-supply-np2031.php');
If you want to assign the file name conditionally, then you'll want the ternary operator:
var $page_products = ($page_name == 'products-uninterruptible-power-supply.php') ?
'products-uninterruptible-power-supply.php' :
'products-uninterruptible-power-supply-np2031.php';

Categories