?: ?? Operators Instead Of IF|ELSE
For [1], you can't: these operators are made to return a value, not perform operations.
The expression
a ? b : c
evaluates to b
if a
is true and evaluates to c
if a
is false.
The expression
b ?? c
evaluates to b
if b
is not null and evaluates to c
if b
is null.
If you write
return a ? b : c;
or
return b ?? c;
they will always return something.
For [2], you can write a function that returns the right value that performs your "multiple operations", but that's probably worse than just using if/else
.
Use of ternary operator instead of if-else in C++
No. In general the conditional operator is not a replacement for an if-else
.
The most striking difference is that the last two operands of the conditional operator need to have a common type. Your code does not work eg with:
std::string do_this() {return {};}
void do_that() {}
There would be an error because there is no common type for void
and std::string
:
<source>: In function 'int main()':
<source>:15:22: error: third operand to the conditional operator is of type 'void', but the second operand is neither a throw-expression nor of type 'void'
15 | my_flag ? do_this() : do_that();
| ~~~~~~~^~
Moreover, the conditional operator is often less readable.
The conditional operator can be used for complicated in-line initialization. For example you cannot write:
int x = 0;
int y = 0;
bool condition = true;
int& ref; // error: must initialize reference
if (condition) ref = x; else ref = y; // and even then, this wouldn't to the right thing
but you can write
int& ref = condition ? x : y;
My advice is to not use the conditional operator to save some key-strokes compared to an if-else
. It is not always equivalent.
PS: The operator is called "conditional operator". The term "ternary operator" is more general, like unary or binary operator. C++ just happens to have only a single ternary operator (which is the conditional operator).
Can we use '?' operator instead of nested-if condition?
You forgot to add a part of the expression. Try it as follows:
int i = (10>5) ? ( (2<5) ? 230:456 ) : 0;
Replace the above 0 to be the desired number you want your variable to be when your first condition (10>5)
is false.
Using the ternary operator instead of if/else?
The ternary syntax is conditional ? true : false
. You've combined multiple if
conditional ternaries here, though no logic for if none of the conditionals are met. To correct this, add fallback behavior of : false
after your final conditional:
var age = 15;
function whichSchool(age) { return (age < 13) ? "Elementary School" : (age >= 13 && age <= 18) ? "Secondary School" : (age > 18) ? "University" : "None"}
console.log(whichSchool(15))
Use Ternary operator instead of if..else in javascript
There are multiple ways to write a conditional statement in JS. However, if there are multiple statements I would say you should stick to if
else if
else
. But if you want to see other approaches, here they are:
Using Ternary operator
? :
const {pr} = req.query
pr === 'trans'
? util.transUrl(req.originalUrl).then(param =>
res.redirect(param)
)
: pr === 'inst'
? util.instaUrl(req.originalUrl).then(param =>
res.redirect(param)
)
: res.status(400).send('Contact the editor of the originating page.')
Using Gate logic
&& ||
const {pr} = req.query
(pr === 'trans' &&
util.transUrl(req.originalUrl).then(param =>
res.redirect(param))
) ||
(pr=== 'inst' &&
util.instaUrl(req.originalUrl).then(param =>
res.redirect(param))
) ||
res.status(400).send('Contact the editor of the originating page.')
Now, Looking at your code, here if and else if statements are similar. So you can avoid else if
using ternary operator like this:
const {pr} = req.query
if(pr === 'trans' || pr === 'inst'){
util[pr === 'trans' ? 'transUrl' : 'instaUrl'](req.originalUrl)
.then(param => res.redirect(param))
}
else{
res.status(400).send('Contact the editor of the originating page.')
}
Just one FYI: Please consider using ===
instead of ==
whenever you are comparing strings and there is no need of coercion.
Ternary operator ?: vs if...else
Depends on your compiler, but on any modern compiler there is generally no difference. It's something you shouldn't worry about. Concentrate on the maintainability of your code.
Using ternary operators instead of if statement when returning variable
Is returning null a proper way to hide Components?
Yes, returning null is a valid return value for a React Component. See this section of the official documentation:
Booleans, Null, and Undefined Are Ignored
false
,null
,undefined
, andtrue
are valid children. They simply don't render.
You could shorten your code a bit though:
const Component = ({data, onChange}) => (
data && data.length ? <ul>
{data.map(( item ) => <Item onChange={ onChange } />)}
</ul> : null
)
Note however that you are not using item
inside <Item>
. Is that intentional? If so, you can write instead: {data.map(() => <Item onChange={ onChange } />)}
Also note that you need to provide a key
property to each <Item>
. I have not added that to my snippet, but you can read more about the key
prop, here.
Javascript usage of && operator instead of if condition
What always helps me is translating it to words
var r = 0;
var i = 10;
r == 0 && (r = i);
translates to
- set variable r to zero
- set variable i to ten
- if variable r equals zero AND the return of the following statement "set variable r to value of variable i"
- do nothing, but r is now 10.
so in short, let's forget about 1 and 2.
In javascript the execution flow in a boolean comparisan is to stop execution of if statement parameters if any part from the && fails.
An boolean comparisan will execute from left to right.
1 == 1 && 2 == 3 && (r = i)
it will pass 1 == 1
fail on 2 == 3
and never reach the assigment operation.
Basically it's a shorthand for:
if(r == 0) {
r = i;
}
Related Topics
How to Get All the Ad Groups for a Particular User
Cannot Find .Cs Files for Debugging .Net Source Code
How to Make the Xmlserializer Only Serialize Plain Xml
How to Change Iis Express Port for a Site
How to See the Raw Http Request That the Httpwebrequest Class Sends
How to Set a Conditional Compile Variable
Enumerating Through an Object's Properties (String) in C#
@(At) Sign in File Path/String
How to Use a C# Class Library in a Project
Recommendations on Parsing .Eml Files in C#
Start May Not Be Called on a Promise-Style Task. Exception Is Coming
With Unity How to Inject a Named Dependency into a Constructor
How Is Memory Allocated for a Static Variable
A Textbox/Richtextbox That Has Syntax Highlighting? [C#]