Best practice for using if () statements

General question relating to all pertinent videos.

I have yet to pick up the subtleties of when to test for true and when to test for false in the if statements. It seems like every time I implement some code, I have done it the wrong way. So the question is, what is best practice?

What I mean is, if I code “if (statement is true) return” then I can almost guarantee the videos will say “if (statement not true) { CODE }” and vice versa (I exaggerate for effect, of course).

Is this simply style, or is there a more subtle reason for the choice?

A lot of it comes down to efficiency and/or structure. For example doing if { } return is a good way to quickly get out of the function if you aren’t going to need it and run all that code for no reason.

Sometimes you might want to put the thing first that is most likely to occur as well. But I bet a lot of the time it’s just preference as well.

1 Like

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms