Hacker News new | ask | show | jobs
by chatmasta 1126 days ago
That's true when you're assigning the result of the function to a variable, but what about the use case where you're replacing a ternary within JSX code? You could extract the evaluation to an assignment of a variable outside of the JSX, but that's the kind of unnecessary complexity that IMO is sometimes worth avoiding.
1 comments

We are being quite abstract here since we are lacking real-life examples here, but using a variabe assignment intead of an inline if/else assertion does not add any complexity at all. It adds more code, yes. More complexity? No. Is it good or bad to add more code? I would answer: the more easily readable and maintainable version of the code is the better version of the code. More times than not, more code is the better version (when it is dry, with correct abstractions and good names).
If you're only consuming the variable once, and it's inside a declarative syntax like JSX, then I'd argue it's more readable to use an anonymous function, because the reader doesn't need to look elsewhere, and the function is defined in the same place where it's evaluated. And you don't need to bother thinking up a name for a variable, which could lead you to prematurely generalize.

Personally, most of the time I assign to a variable. But I do think there are cases where the IIFE is an appropriate and more elegant approach.