10 ms·
a function _if(cond, a, b) would probably have been better.
by paddw 3y ago
a function _if(cond, a, b) would probably have been better.
- danShumway 3y agoBeat me to it :) It's not the biggest thing in the world, and I don't want to distract from the rest of the book, but this is a situation where writing a one or two line helper function: const _ = (cond, a, b) => cond ? a : b; would have made the code much more readable without much downside that I can see -- at least to my subjective opinion. Maybe I'm missing something. Edit: comment below correctly points out that if it's important for you to avoid immediate evaluation, you'll need to wrap your conditionals in functions.
- Jtsummers 3y agoJS is not lazily evaluated so that means `a` and `b` would both be evaluated regardless of the result of the cond expression. To make a proper version you have to complicate things by calling it like this: _(cond, () => a, () => b) And _ becomes: const _ = (cond, a, b) => cond? a(): b(); And it does matter in this case when looking at the last condition which signals an error (does not return an error value if I understand it correctly). In which case your _ would raise an error even when not appropriate.
- danShumway 3y agoThat is an excellent point, thanks for pointing that out. I'm not sure it matters here, the error you're pointing out looks to be getting returned (unless I'm misunderstanding what the book intends the `error` function to do), and creating an Error in Javascript is fine, it doesn't break your program until it's actually thrown. Edit: just looked at your comment again, and you're saying it does actually throw the error rather than returning it :) So double-corrected on my part :) But your point stands regardless. There will be scenarios where what you're talking about matters -- JSX also follows this pattern of immediate evaluation and yeah, I see errors from that plenty of times. So it's good to mention.
- afiori 3y agoThere is an example in the book showing why this would not work, in short it is because js is not lazy