Yes, it is a valid syntax to write a do expression without an else and it will return an undefined
(void 0
).
let a = do {
if (false) true
}
// a === undefined
We can also return a value at the end without even using else
like this:
let a = do {
if (false) true
null
}
// a === null
Especially for ReactJS, we have to return a null
even using the do expression, because if it doesn't return something, the return value will be undefined
which of course will error break the component rendering:
export default function myComponent(props) {
return (
<div>
{do {
if ([condition]) {
<p>If statement is true</p>
}
null
}}
<p>I am always rendered</p>
</div>
);
}
Or, use the Nullish coalescing operator ??
which will also catch undefined
:
export default function myComponent(props) {
return (
<div>
{do {
if ([condition]) {
<p>If statement is true</p>
}
} ?? null}
<p>I am always rendered</p>
</div>
);
}
Other answers here suggest why bother using do expression since we can do this using the Conditional (ternary) operator ?:
, and the answer is that using the ternary operator when we'll have more than one condition won't be syntactical friendly and it will lead in miss-renders and hard time understanding the logic for developers:
export default function myComponent(props) {
return (
<div>
{[condition1]
? <p>If condition1 is true</p> :
[condition2]
? <p>If condition2 is true</p> :
[condition2]
? <p>If condition3 is true</p> :
[condition4]
? <p>If condition4 is true</p> :
null
}
<p>I am always rendered</p>
</div>
);
}
and that's one of the reasons behind the proposal and existence of the do expression; it will make multiple conditional expressions syntactical friendly:
export default function myComponent(props) {
return (
<div>
{do {
if ([condition1]) <p>If condition1 is true</p>
if ([condition2]) <p>If condition2 is true</p>
if ([condition3]) <p>If condition3 is true</p>
if ([condition4]) <p>If condition4 is true</p>
} ?? null}
<p>I am always rendered</p>
</div>
);
}
do
expression is a stage 1 proposal, not part of ES2016 (ES7). – Tried