Some time ago, I put a comment during a code review which led to a bug in our React Native App.
I suggested a fellow developer to replace ternary operator with logical &&
in favour of writing shorter, more readable code. BIG MISTAKE.
Besides the fact that shorter code is not always better. There is also a subtle difference between the two statements below:
mightExist && <p>DEFAULT</p>
and mightExist ? <p>DEFAULT</p> : null
which we didn't realise immediately.
Ternary Operator
A simplified representation of the code snippet what was reviewed is this:
export default function App() {
const arr = [];
return <div className="App">{arr.length ? <p>NOT EMPTY</p> : null}</div>;
}
arr.length
is 0 which is falsy
and the above JSX renders an empty div
.
Logical &&
It was suggested to use logical && instead of ternary operator above.
export default function App() {
const arr = [];
return <div className="App">{arr.length && <p>NOT EMPTY</p>}</div>;
}
&&
operator short circuits to return the value of the first falsy operand it encounters. If all operands are falsy, it will return the last truthy value.
Keeping that in mind, the above JSX renders a div which has 0 inside it. This is definitely not the behaviour we are expecting and could have been avoided.
React Native
While the above would lead to a 0
being printed unintentionally on React Apps, for React Native apps it had bigger implications.
export default function App() {
const arr = [];
return <View className="App">{arr.length && <Text>NOT EMPTY</p>}</View>;
}
In React Native, text strings must be rendered inside Text
components. The above JSX violates this, since 0 is inside directly a child of View
component. This would break the UI and app would crash incase the error is not handled.
Notes
The above bug went unnoticed also because the name of the variable which held the value arr.length
was not self explanatory and it didn't occur to us immediately that the value could be 0. This shows why appropriate naming of variables is very important for effective development.
Top comments (0)