Can i use multiple line in ternary operator - javascript

I want to use the if else statement in the ternary operator
if (open) {
setOpen(false)
} else {
setOpen(true)
navigator.clipboard.writeText(link)
}
There is no problem in "if" I cant figuring out how to convert else to ternary. Like something the code below:
open ? setOpen(false) : setOpen(true) ; navigator.clipboard.writeText(link)
Something like this or is there another method to do the job?

Don't.
You're trying to use the ternary conditional operator for the wrong reason. It is not a drop-in replacement for any if block.
The ternary conditional operator is an expression. It resolves to a value, which can be used elsewhere. For example:
let x = someCondition ? 1 : 0;
The expression resolves to a value, either 1 or 0, and that value is used in an assignment statement.
The code you're showing is not an expression. What you have is a series of statements, conditionally executed based on some value. An if block is a structure for conditionally executing statements.
The code you have now is correct.

Yes, it's possible to write multiple statements in ternary if else cases:
The format is:
condition ? codeLine1 : ( codeLine2 , codeLine3 )
Which makes your statement as:
open ? setOpen(false) : (setOpen(true), navigator.clipboard.writeText(link));
Combine multiple statements in parenthesis separated by commas in between each line.
That being said it's recommended to use old fashioned way of if-else statement if multiple statements are involved.
Please select answer if it helps and let me know if any questions.

Yes. it is possible (although not a best practice and not recommended)
they way to to it is by:
Put everything inside parenthesis
Seperate each statement with comma (",")
e.g:
condition ? statement1 : ( statement2, statement3, statement4 )
Try this snippet:
let a = 1;
let b = 1;
a == b ?
(console.log("they"),console.log("are"), console.log("equal")) :
(console.log("they're"), console.log("not equal"));

Related

Ternary operator multiple statements [duplicate]

This question already has answers here:
Javascript - Ternary Operator with Multiple Statements
(5 answers)
Closed 3 years ago.
I want to do multiple things if the condition is true or false. I tried to wrap the statements in a { } but it doesn't work. So my code:
theId == this.state.correctId ?
console.log("Correct Id!") :
console.log("TRY AGAIN")
I tried:
theId == this.state.correctId ?
{console.log("Correct Id!"); //semicolon does not make any difference
this.setState({counter: this.state.counter+1})
} :
console.log("TRY AGAIN")
This doesn't work. How do I add multiple statements if the condition is true or false?
Thanks.
The conditional operator should only be used when you need to come up with an expression that is (conditionally) one thing or another, eg
const something = cond ? expr1 : expr2;
Because that's not the case here (and you want to log or call setState), the conditional operator is not appropriate; use if/else instead:
if (theId == this.state.correctId) {
console.log("Correct Id!")
this.setState({counter: this.state.counter+1});
} else {
console.log("TRY AGAIN");
}
You could technically slightly tweak your original code by using the comma operator to combine expressions:
theId == this.state.correctId
? (
console.log("Correct Id!"),
this.setState({counter: this.state.counter+1})
)
: console.log("TRY AGAIN");
But that's very hard-to-read, and is not what a reader of your code would expect to see from the conditional operator, so should probably be avoided.
Using the conditional operator when the resulting expression is not going to be used should probably be reserved only for code-golfing and minifying, but not in professional source code, where readability is extremely important.
You can use the comma operator, like this:
const ret = true ?
(console.log("1"),
console.log("2"),
"3")
: console.log("nope");
console.log(ret);

How do i use nested ternary operator in my code? Javascript

Trying to use nested ternary operator in my code
Code:
let ele_Partition = records[0].data.meeting ?
records[0].data.meeting.partition : records[0].data.partition;
Need to add another data for the same condition.
records[0].data.meeting.meetingPartition
How to implement it without nested if-else?
let ele_Partition = records[0].data.meeting ?
records[0].data.meeting.partition : records[0].data.meeting.meetingPartition ?
records[0].data.meeting.meetingPartition : records[0].data.partition;
If records[0].data.meeting, set the variable to records[0].data.meeting.partition.
Else if records[0].data.meeting.meetingPartition, set the variable to records[0].data.meeting.meetingPartition
Else set the variable to records[0].data.partition.
You should avoid nested ternary operators as they make your code incredibly complicated to read.
I would take a single ternary with a default value
let ele_Partition = records[0].data.meeting
? records[0].data.meeting.partition
: records[0].data.meeting.meetingPartition || records[0].data.partition;

React JSX in className if-else syntax [duplicate]

This question already has answers here:
if-else statement inside jsx: ReactJS
(17 answers)
Closed 4 years ago.
I am currently working on a react app where I am adding and changing classes based on certain state changes. It worked successfully in testing with a ternary operator but now I realized I will have to add mutiple else-if statements so I am trying to convert it to a classic if else format but am getting syntax errors and I'm not sure how to do it.
Here is the ternary operator that worked fine:-
<div className={"wrapper " + (this.state.hot ? 'wrapper-gradient-hot' : 'wrapper-gradient-cold')}>
Here is my attempt to make it a classic if-else in JSX and failed:-
<div className={"wrapper " + (
if (this.state.hot) {
return 'wrapper-gradient-hot';
} else {
return 'wrapper-gradient-cold';
}
)}>
Pls help me out :)
You can only use expressions inside of a React Component attribute. You'll need to move your logic into a function.
function temperatureClassname(temp){
const prefix = 'wrapper-gradient-'
switch (temp) {
case 'hot': return prefix + 'hot'
case 'cold': return prefix + 'cold'
case 'ice-cold': return prefix + 'too-cool'
}
}
And your react component would look like this:
<div className={ temperatureClassname(this.state.hot) }>
If and else statements, are just that... statements. Inline JSX expressions that you wrap with {…} only allow expressions; statements are not expressions.
Your ternary approach is fine, though since there's some commonality between the two strings you can actually use interpolation:
<div className={`wrapper-gradient-${this.state.hot ? 'hot' : 'cold'}`}>
One approach you could adopt is to handle this outside of your JSX. So, in your render function still but just above where you return.
render() {
let gradientValue;
// Put your if-else here and update gradientValue on each condition.
return (
<h1 className=`wrapper ${gradientValue}`>Your html here</h1>
);
}
return only returns values from inside a function, just putting parentheses around an if/else statement like that isn't going to work. You'd be better off sticking with the ternary operator, and nesting them as required.

JavaScript shorthand if statement, without the else portion

So I'm using a shorthand JavaScript if/else statement (I read somewhere they're called Ternary statements?)
this.dragHandle.hasClass('handle-low') ? direction = "left" : direction = "right"
This works great, but what if later I want to use just a shorthand if, without the else portion. Like:
direction == "right" ? slideOffset += $(".range-slide").width()
Is this possible at all?
you can use && operator - second operand expression is executed only if first is true
direction == "right" && slideOffset += $(".range-slide").width()
in my opinion if(conditon) expression is more readable than condition && expression
Don't think of it like a control-block (ie: an if-else or a switch).
It's not really meant for running code inside of it.
You can. It just gets very ugly, very fast, which defeats the purpose.
What you really want to use it for is ASSIGNING VALUES.
Taking your initial example and turning it on its head a little, you get:
direction = (this.dragHandle.hasClass("handle-low")) ? "left" : "right";
See. Now what I've done is I've taken something that would have required an if/else or a switch, which would have been used to assign to that one value, and I've cleaned it up nice and pretty.
You can even do an else-if type of ternary:
y = (x === 2) ? 1 : (x === 3) ? 2 : (x === 4) ? 7 : 1000;
You can also use it to fire code, if you'd like, but it gets really difficult after a while, to know what's going where (see the previous example to see how even assignment can start looking weird at a glance)...
((this.dragHandle.hasClass("...")) ? fireMe(something) : noMe(somethingElse));
...this will typically work.
But it's not really any prettier or more-useful than an if or a branching, immediately-invoking function (and non-JS programmers, or untrained JS programmers are going to crap themselves trying to maintain your code).
The conditional operator is not a shorthand for the if statement. It's an operator, not a statement.
If you use it, you should use it as an operator, not as a statement.
Just use a zero value for the third operand:
slideOffset += direction == "right" ? $(".range-slide").width() : 0;
What you have will not work, but why not just use a one line if statement instead.
if(direction == "right") slideOffset += $(".range-slide").width();
This involves less typing than the method Ray suggested. Of course his answer is valid if you really want to stick to that format.
No, This is not possible, because ternary operator requires, three operands with it.
first-operand ? second-operand (if first evaluates to true) : third-operand (if false)
you can use && operator
direction == "right" && slideOffset += $(".range-slide").width()
This doesn't exactly answer your question, but ternaries allow you to write less than you've shown:
direction = this.dragHandle.hasClass('handle-low') ? "left" : "right";
And now that I think about it, yeah, you can do your question too:
slideOffset + direction == "right" ? = $(".range-slide").width() : = 0;
This is a theory. The next time I have an opportunity to += a ternary I will try this. Let me know how it works!
You can use this shorthand:
if (condition) expression
If in some cases you really want to use the if shorthand. Even though it may not be the best option, it is possible like this.
condition ? fireMe() : ""
Looks weird, does work. Might come in handy in a framework like Vue where you can write this in a template.
You can using Short-circuit Evaluation Shorthand. if you want the if condition just write the else condition.
let
a = 2,
b = a !== 2 || 'ok';
console.log(b);

Ternary Operator in JavaScript With Multiple Expressions?

the_styles ? the_styles.appendTo('head'); the_styles=null : the_styles = $('.stylesheet').detach();
Obviously, this isn't valid. Notice the ";" between the appendTo() and the_styles=null. How do I write it on 1 line and still have multiple expressions like that?
Use the comma operator this way:
the_styles ? (the_styles.appendTo('head'), the_styles=null) : the_styles = $('.stylesheet').detach();
Here's what the Mozilla Developer Center writes about the comma operator:
You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.
Read more here: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Comma_Operator
Who needs the ternary operator?
​the_styles = !the_styles && $('.stylesheet').detach()​​​​ ||
the_styles.appendTo('head') && null;​
Had to switch the expressions around as otherwise the null value of the first expression will always force the second expression .detach() to be evaluated.
The only thing about clever code is that once you come back to it after a coffee break, it won't make any sense even to you. So this is much better:
if(the_styles) {
the_styles.appendTo('head')
the_styles = null;
}
else {
the_styles = the_styles.detach('.stylesheet');
}
To me, even the above simplistic version doesn't make any sense. The what part is obvious, but why is it doing that?
the_styles ? (function() {the_styles.appendTo('head'); the_styles=null})() : <etc>
Just wrap the code block in (function() { and })().
Now for the hard part: why would you want to do this? Perhaps there's a better solution!
i agree with glowcoder but if you still want it:
the_styles ? function(){ the_styles.appendTo('head'); the_styles=null;}() : the_styles = $('.stylesheet').detach();
the_styles ? the_styles.appendTo('head') : the_styles = $('.stylesheet').detach();
you dont need to null it if your overwriting it !
the_styles=the_styles || $('.stylesheet').detach(); the_styles.appendTo('head');

Categories

Resources