I always go with Statement B. This is known as "early returns" and helps with confusing success/error cases. Take for example:
functioncreatePost(post){// Earliest potential error if no post is provided.if(!post)returnfalse;// Ensure correct data type.if(typeofpost!=='object')returnfalse;// Ensure required data is provided.if(!post.title||!post.body)returnfalse;// We're all good at this point. Assume it's safe to create the post!constisPostCreated=create(post);returnisPostCreated;}
It's nice to know for sure that the end of the function where we're saving the post to the database will not error out due to bad data, since we already verified those cases earlier.
I like this style more - it looks clearer to me, and from the point of working through the logic, I like that the returns just end the function.
If a block just set a value and returned it later, there's a chance it could be reassigned in another buggy block, so I think there's less risk in this style too.
I always go with Statement B. This is known as "early returns" and helps with confusing success/error cases. Take for example:
It's nice to know for sure that the end of the function where we're saving the post to the database will not error out due to bad data, since we already verified those cases earlier.
I like this style more - it looks clearer to me, and from the point of working through the logic, I like that the returns just end the function.
If a block just set a value and returned it later, there's a chance it could be reassigned in another buggy block, so I think there's less risk in this style too.
This looks great to me. I'd be happy even without the comments as it feels pretty self-documenting.
I added the comments just for the sake of the example, but they should definitely be removed for a real app.