Ternary operator multiple statements [duplicate] - javascript

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

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

"Do nothings" as statment in Javascript Condition

I want a ternary operator in JavaScript to return nothing if the statment is false
I have tried this:
1 == 1 ? alert('YES') : '';
But I want to know if this is the right way to make a statments "DO NOTHING" depending on the condition.
No, use if.
if (1 == 1) {
alert('YES');
}
Don't abuse the conditional operator as a replacement for if/else - it's confusing to read. I'd also recommend always using === instead of ==.
If you really want to do it, && will be one way.
1 == 1 && alert('ALERTED');
1 == 2 && alert('NOT ALERTED');
It is single statement.
A condition after an AND operator is only run if the first is true. So it is like an if statement.
did you try a single line if statement without brackets?
if(1 == 1) alert('Yes');

Array push with ternary operator

I want to push an error message to a field if it is invalid.
this code works
let message = [];
if (!isvalid) {
message.push("Please enter a value");
}
How can I achieve this with ternary operator.
The way I did.
message.push((!isvalid) ? "Please enter a value" : null)
But this code is also pushing null to the array.
like:: message=[null]
Honestly, it's not a good way to do it. It does not make sense to use a ternary where one logical branch of the condition leads to ...do nothing. Ternary only makes sense where you want to return one of two values depending on the condition.
If you want to be concise you could use:
!isValid && message.push('foo');
though some linters won't like you for it. It has the disadvantage that it is less readable than a simple if. If you must use the ternary, you could also do this:
!isValid ? message.push('Please enter a value') : void 0; // or null
but it's ugly and bad because of that useless hanging false branch of the ternary expression. Don't do it.
Can you try (!isvalid) ? message.push("Please enter a value") : null ?

Javascript Shorthand to Check if val Equals One of Two [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Closed 5 years ago.
I feel like I come across this a lot and that intuitively, there should be a way to do something like this:
if (userType ==="admin" || userType === "superUser"){
// do stuff
}
In a more elegant way, like this:
if (userType === ("admin" || "superUser")){
// do stuff
}
Obviously that^ doesn't work because if the first value resolves to true, it will never check if it's the second ("superuser").
Is there shorthand to do this in a JS if-statement where you wouldn't have to repeat the variable name?
Switch statements don't count! ;D
JavaScript doesn't provide out of the box such a syntax.
Now, you can do something of close enough with the Array.includes() method.
It returns true if the element is found in the array.
Otherwise if returns false.
var userTypes = ["admin", "superUser"];
if (userTypes.includes(userType)){
// do stuff
}
or by inlining the array value :
if (["admin", "superUser"].includes(userType)){
// do stuff
}
you can use an array with indexOf. something like
if(["superUser", "admin"].indexOf(userType) >= 0){
//code goes here
}
You could use an object for fast checking.
if ({ admin: 1, superUser: 1 }[userType]) {
// do something if true
}

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