This is what my ternary looks like now, but I'd like to see how this looks as an if/else block
function showResultBox(v){
v ? searchResultBox() : hideBox()
}
A ternary is way of formatting a conditional that is limited to just an if | else. That is, there is no room for any else if blocks.
Here is what's happening in v ? searchResultBox() : hideBox():
1 2 3
Evaluate v for truthiness.
If v is truthy, call the searchResultBox function.
Otherwise, call the hideBox function
As a non-ternary conditional, your example would look like this:
if (v) {
searchResultBox();
} else {
hideBox();
}
You can experiment with the following examples (fiddle here) to get a better feel for what's going on:
true ? console.log("stark") : console.log("baratheon")
false ? console.log("stark") : console.log("baratheon")
Related
I want to check for an element's existence in the if statement condition, and if so then use the element as part of the comparison. Something like this:
if( if($(".element").length > 0) { $.contains( $(".element")[0], $("[ele]")[0] )} ) {...
I know I could just nest if statements, like:
if($(".element").length > 0) {
if($.contains( $(".element")[0], $("[ele]")[0] )) {....
But is there a shorter way to do this? Can if statements be used in another if statement's condition like this in some way?
You can use the && operator to chain both of your conditions:
if($(".element").length > 0 && $.contains( $(".element")[0], $("[ele]")[0] )) {
If the the first condition fails (code prior to &&), it will short out and not execute the second condition.
You can use the && (and) operator for that. If the thing on the left side of the && is false, then it doesn't evaluate the right side of &&, so you don't have to worry about any errors from the element not existing. (This is called short-circuit evaluation, and || (or) does a similar thing, except || doesn't evaluate the right side if the left side it true.) So
if($(".element").length > 0 && $.contains( $(".element")[0], $("[ele]")[0] )) ...
It's not necessary here, but if you want an if-else inside an expression, you can use the ?: (ternary conditional) operator. condition ? a : b is like if(condition) a else b, except it's actually an expression, so for instance, x = (condition ? a : b) is the same as if(condition) x = a; else x = b;.
I have conditional parameters on ui-router because I am using the same screen in different places in an app. I have to write logic to check which $stateParams value I have assigned to paramId. I have tried with if and else.
Is there a better approach to achieve this task?
$scope.challengesDTO = {
challengeTypeLkupCode: 'RA_CHLNG_TYP_PRC'
};
var paramId = $stateParams.processId ? $stateParams.processId : $stateParams.assessmentId;
if ($stateParams.processId) {
$scope.challengesDTO.challengeTypeLkupCode = 'RA_CHLNG_TYP_PRC'
} else if ($stateParams.assessmentId) {
$scope.challengesDTO.challengeTypeLkupCode = 'RA_CHLNG_TYP_RSKASES'
}
Consider The Null-Coalescing Operator
You should be able to replace your ternary operator with the null coalescing operator in Javascript ||, which essentially a logical 'OR' statement :
// This will set it to processId (if available), otherwise assessmentId
var paramId = $stateParams.processId || $stateParams.assessmentId;
A Ternary (if you want one)
However, if you were just worried about setting your challengeTypeLkupCode property, you could use the following, which would set it depending on if processId existed or not :
// Set your lookup type depending if processId exists or not
$scope.challengesDTO.challengeTypeLkupCode = ($stateParams.processId) ? 'RA_CHLNG_TYP_PRC' : 'RA_CHLNG_TYP_RSKASES';
For readability purposes, you may be best off just using an if statement as seen in your initial code.
For the if else condition u mentioned above u can try-
$scope.challengesDTO.challengeTypeLkupCode=$stateParams.processId?'RA_CHLNG_TYP_PRC':$stateParams.assessmentId?'RA_CHLNG_TYP_RSKASES':"Default value u want to give";
The first part goes with a logical OR ||
var paramId = $stateParams.processId || $stateParams.assessmentId;
The second part is with a nested ternary operator ?: and returns the value itself if no comparison becomes true.
$scope.challengesDTO.challengeTypeLkupCode = $stateParams.processId ?
'RA_CHLNG_TYP_PRC' :
$stateParams.assessmentId ?
'RA_CHLNG_TYP_RSKASES' :
$scope.challengesDTO.challengeTypeLkupCode;
Say we have nested ternary statements:
return foo ? 1 : bar ? 2 : 3;
What is the best way to format this code to ensure future readability by others.
This post is the most popular opinion I could find on this. The suggestion there is
return foo ? 1 :
bar ? 2 :
3 ;
return foo ? 1 : (bar ? 2 : 3) ;
To separate function
function getValue(cond1, cond2) {
if(cond1) return 'a';
if(cond2) return 'b';
return 'c';
}
function work() {
const result = getValue(/* some params */);
}
I can't tell if this is accepted or not but i use it this way all the time.
Ternary gives you such a natural testing structure that you can make the code very readable just by making it multiline and indenting properly. I strongly believe that the following usage of ternary is the best manifestation of a nested conditional.
return foo ? 1
: bar ? 2
: 3;
In more complicated cases you can make ternary and comma operator work together beautifully. Keep in mind that the last instruction in a comma separated group gets returned automatically. Super handy for ternary.
return foo ? ( doSometingFoo()
, variable++
, collectResult() // and return foo result
)
: bar ? ( doSomethingBar()
, variable--
, collectAnotherResult() // and return bar result
)
: ( doSomethingReject()
, variable = 0
, rejectSomehow() // and return error code
)
I have a preference for the readability of this style of ternary operator formatting:
return foo
? bar
: baz
? qux
: qiz
? 1
: 2;
For readability just stay away from those statements, they're very easy to misread, if you want something more readable just expand and use normal statments..
Nothing wrong with just having a nested if statement list..
if(foo){
return 1
}else{
if(bar){
return 2;
}else{
return 3;
}
}
Below is the piece of code I'm having a problem with. I get the JShint "Expected an assignment or function and instead saw an expression".
function checkVal(inputField) {
( inputField.val() === '' ) ? inputField.prev('.cd-label').removeClass('float') : inputField.prev('.cd-label').addClass('float');
}
});
The warning is telling you that the following line could be a mistake or bug:
( inputField.val() === '' ) ? inputField.prev('.cd-label').removeClass('float') : inputField.prev('.cd-label').addClass('float');
Its an expression using the ternary operator that returns the value after the ? if the expression before it is true, or the value after the : otherwise. So basically, it's like a shorthand if statement that results in an assignment.
To remove the warning, you need to assign it to a variable like this:
var yourVariable = ( inputField.val() === '' ) ? inputField.prev('.cd-label').removeClass('float') : inputField.prev('.cd-label').addClass('float');
However, for your case you probably don't really want to assign this to anything, so you should just use an if statement instead.
You should be using an if block here.
if( inputField.val() === '' ){
inputField.prev('.cd-label').removeClass('float');
}
else{
inputField.prev('.cd-label').addClass('float');
}
The ternary operator (?:) should only be used in a context where it returns a value. Such as:
var x = condition ? 'a' : 'b';
Can the javascript shorthand for if-else return out of a function? If so how would this work.
eg.
I have this:
if(boolean){
return;
}
and I would like to write it as this:
(value)? return;
Chrome complains that return is unexpected. Is there anyway to write something like this so that it is valid?
No, you can't do that unless you return a value. For example if your function had to return a value you could have written:
return boolean ? 'foo' : 'bar';
But you cannot stop the execution of the function by returning void using the conditional operator.
If you intend to return from the function at this point in its execution regardless of whether the test evaluates true or false, you can use,
return (value) ? 1 : 2;
But if you merely wish to return early when a test evaluates true (for instance, as a sanity-check to prevent execution when parameters are invalid), the shortest you can make it is:
if (boolean) return;
if(boolean) return;
Single line , readable , perfectly valid;
I know it's an old question but I want to add that there is a non-standard way to return out of a function in shorthand if-else, and that is performing Immediately Invoked Function Expression (IIFE):
function outOfFunction(boolean){
return (boolean)?(()=>{return true;})():(()=>{return false;})();
}
console.log(outOfFunction(true));
console.log(outOfFunction(false));
And if we want to be out of the function or continue with other task:
function shorthandExampleJustTrue(boolean){
var someVar = "I'm out";
return (boolean)?(()=>{return true;})():(()=>{
console.log("here my code ");
console.log(someVar);
return "anythig else";
})();
}
console.log(shorthandExampleJustTrue(true));
console.log(shorthandExampleJustTrue(false));
When we use arrow functions we are able to access to variables out of the immediate function context.
You want to do a ternary operator
which is this:
(bool) ? ifTrue : ifFalse;
Please note: you cannot omit the else portion of a ternary operator.
http://en.wikipedia.org/wiki/Ternary_operation
The conditional "ternary operator" (condition ? expression to evaluate when true : expression to evaluate when false) is often used for simple conditional variable assignment.
if you need :
if( x > 0) {
a = 10;
}else{
a = 30;
}
you can write:
a = (x>0)? 10 : 30;
You can think of it like a simple function, which takes 3 parameters (p1, p2, p3), if p1 is true it returns p2 and if p1 is false then it returns p3.
(p1)? p2 : p3;
And just like such a function, there's no way for it to cause the parent function to return based on the condition. It is not therefore a shorthand for if/else.
if I'm not mistaken you're talking about this right? a short-hand.
return (if the value here is true then ->) && false
example:
const isGood = true && "yeah";
console.log(isGood) //yeah
Use this as your short hand if the value is true then it will return false; using the && operator is better