getify / Functional-Light-JS

Pragmatic, balanced FP in JavaScript. @FLJSBook on twitter.
http://FLJSBook.com
Other
16.64k stars 1.96k forks source link

Unassigned variables should be compared to undefined rather than null #24

Closed jtrimble closed 7 years ago

jtrimble commented 8 years ago

Yes, I promise I've read the Contributions Guidelines.

Admittedly, this is a minor quibble. But since this is a teaching text I'll mention it for your consideration.

In Chapter 2, the section on early returns, your example program that has been refactored to have a single return, gates each assignment to retValue with an if (retValue == null && ...). Since no assignment has ever been made to retValue, it's actual value is undefined and it is coerced into a null by the equality operator. This works, but seems unnecessarily fragile when you could either explicitly set retValue = null in your declaration, or you could compare directly to undefined. Any time == would cause my program to do one thing and === would cause my program to do another, I become a little concerned.

getify commented 8 years ago

Thanks for the feedback... I'll take it into consideration. :)

gagyibenedek commented 6 years ago

One more thing to add: why are you doing the retValue == undefined check in the first if? The var was not used yet, so it'll always be undefined.

getify commented 6 years ago

for symmetry sake.

gagyibenedek commented 6 years ago

hmm, that's a strange reasoning. Why give the reader and the cpu an extra thing to process and think about, when it's not needed? I mean it has minor importance, I consider it 100% fine either way, just wanted to check if it was there on purpose.

getify commented 6 years ago

think of it this way: with early-return style, you can just insert a new line of return code anywhere, even at the top of the function, and not have to change any other lines of code.

if the first IF doesn't have the undefined check, then there's a refactoring hazard in that respect. I think it's better to prevent rather than trip over it.