I have a question about the proposed JavaScript do expression construct. There are many examples that show how it can be used to return a value from a conditional statement that has both if
and else
. Also valid for if
with else if
and else
.
What about a conditional that has just an if
clause but no else if
or else
? Is this valid usage of the do
expression?
My use case is for conditionally displaying content in a React component. I would like to write JSX code like so, but I am not sure if it is valid:
export default function myComponent(props) {
return (
<div>
{do {
if (true) {
<p>If statement is true</p>
}
}}
<p>I am always rendered</p>
</div>
);
}
I also asked the question in this gist.
An if statement looks at any and every thing in the parentheses and if true, executes block of code that follows. If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed.
So I hope not tl;dr the first questions answer is no, a else can follow after an if but it does not need to, the other way is completely prohibited (else without if), makes sense as this would mean do it in all cases, where you would not need a condition, so it is expected to be an unwanted error.
Conditional statements control behavior in JavaScript and determine whether or not pieces of code can run. There are multiple different types of conditionals in JavaScript including: “If” statements: where if a condition is true it is used to specify execution for a block of code.
Not sure about do
, also as mentioned by @Felix Kling
do expression is a stage 1 proposal, not part of ES2016 (ES7).
You can write it like this using ternary operator, and return null
if condition fails:
export default function myComponent(props) {
return (
<div>
{
true?
<p>If statement is true</p>
:null
}
<p>I am always rendered</p>
</div>
);
}
Or Use && Operator:
export default function myComponent(props) {
return (
<div>
{
true && <p>If statement is true</p>
}
<p>I am always rendered</p>
</div>
);
}
Check the DOC for more details about Conditional Rendering.
Why not simply do this ? Using the Ternary operator
export default function myComponent(props) {
return (
<div>
{ true ? <p>If statement is true</p> : null }
<p>I am always rendered</p>
</div>
);
}
Here is what Babel does:
Input:
<p>
{do {
if (true) {
<a/>
}
}}
</p>
Output:
React.createElement(
"p",
null,
true ? React.createElement("a", null) : void 0
);
This makes sense to me. The return value in the implied else
would be undefined
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With