Ternary Operator in JavaScript With Multiple Expressions? - javascript

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');

Related

Can i use multiple line in ternary operator

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"));

Is it possible to use the ternary operator for an if, if else, without a final else?

I've recently become informed of the ternary operator and it seems like an effective way of cleaning up my code. However, I seem to be confused with the possibilities of it.
I understand that you cannot use it for if-only conditions, but I'm a little confused about the logic of what I've done.
I wrote this:
if(current_slide < 1){
current_slide = 1;
ToggleEnabled(next_button);
}else if(current_slide > total_slides){
current_slide = 1;
ToggleEnabled(prev_button);
}
It works, whatever. I wanted to clean it up a little, so I made this:
current_side < 1 ? (ToggleEnabled(next_button), current_slide = 1) : current_slide > total_slides ? (ToggleEnabled(prev_button), current_slide = 1) : [No clue what to put here];
Is there a better way of doing this in a more tidy way, or should I just keep using the if-elseif- ?
In my opinion the ternary operator should not be chained. As #VLAZ expressed their concerns in their comment, the ternary can become excessively difficult to read if you chain it in multiples. In this situation I would stick with the traditional if-else.
Take a look at the following:
if (condition1) {
// do stuff #1
} else if (condition2) {
// do stuff #2
} else if (condition3) {
// do stuff #3
} else {
// do stuff #4
}
And compare the readability to the same in ternary (I tried to indent it clearly, but chained ternary formatting is a matter of opinion):
condition1
? // do stuff #1
: condition2
? // do stuff #2
: condition3
? // do stuff #3
: // do stuff #4
To my eye the first option is a lot more readable. There is not much to be gained even if you would understand chained ternary very well, as it is (slightly) less efficient than traditional if-else.
Also of note should be the fact that ternary always needs the both the ? and the :, which means there is always a "final else" that you must deal with.
IMO, the ternary operator is meant to choose between answers or values, based on a condition, e.g.:
const x = condition1 ? 1 : 2;
return condition2 ? func1(x) : func2(x);
If you don't use the resulting value from a ternary expression (as you do) then the usage becomes highly suspect to me, and I would most likely ask it to be changed in code review. Even more so if you move the assignment part to BEHIND the ? and : selectors as you did.
Not everything that is possible, is also good style, good practice or recommended.

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;

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);

Is it safe to run code inside the conditional operator?

I often see and use codes like:
var myvar = (1 < 2) ? 3 : 4 ; //if 1 < 2 then myvar = 3, else = 4
But I just recently saw a code that was executing code, just like some kind of replacement for the if(){}else{}:
Example:
(1 < 2) ? alert("example1") : alert("example2");
The first thoughts that came to me were, "wow, this is like 6-7 characters shorter", "endless of possibilities" or "this made my day".
My question:
Is this thing error-free and safe to use? (like, with a lot of code inside, and nested stuff)
For now, I will just keep using it in the normal way, I have the fear that if I start using it to execute pieces of code might not work.
Is this thing error-free and safe to use? (like, with a lot of code
inside, and nested stuff)
Yes. However, the more code that's within it, the less readable it becomes.
I prefer to use it (the conditional operator) for short, concise statements. Anything more complex deserves an if/else for the sake of readability and maintainability.
There are some exceptions. You can't do this with:
break
continue
Any block like if, for, while, do, or try
for example. What's more, it can mess with your order of operations:
x < 3 ? l = true : r = true; // Syntax error, = has lower precedence than ?:
But that's not the reason not to do it, it's because it's ugly. Which one is clearer to you, this:
if(i > 5) {
alert('One');
} else {
alert('Two');
}
or
i > 5 ? alert('One') : alert('Two');
? It's not quite right, is it? And saving characters is never a reason to do anything, really; otherwise there would be no comments or whitespace. A good minifier like Google Closure Compiler will automatically convert these for you when possible, and there are plenty of other places to save. In the end, it's just whatever you find most convenient and readable.
Also, if you do end up needing break, continue, etc. then it's going to be rather inconsistent and unattractive code.
You're referring to the ternary operator. It's usually used for setting variables with simple strings like this:
var phone = old ? "blackberry" : "iPhone"
That much simpler than using an if:
var phone = "iphone"
if (old) {
phone = "blackberry"
}
It's good in this context, in the example you described and as soon as it starts getting confusing or I'd definitely not recommend it!
Your example might be made better like this:
var msg = 1 < 2 ? "alert1" : "alert2";
alert(msg);
You could also write:
alert( 1<2? "example1" : "example2" );
The ternary opertator is designed for simple cases, sometimes developers get carried away and use it to replace multiple if..else statements, e.g.
var someVal = foo < bar? 'yes' : bar > fum? : fum : fi != fee? fi : fee;
which is not a good idea IMHO.

Categories

Resources