3 ms·
One thing I've always done with if statements is when I have an if with a negated condition and no else case if (!condition) { // do stuff } Whe
by michaelmior 10y ago
One thing I've always done with if statements is when I have an if with a negated condition and no else case
if (!condition) {
// do stuff
}
When I want to add an else case, I swap the order so the condition is no longer negated.
if (condition) {
// do other stuff
} else {
// do stuff
}
To me it's easier to read a non-negated condition and the else case then feels more natural. (It avoids having to internally think about else case as "condition not not satisfied".)
- mercer 10y agoInteresting. I often (but not always) prefer the if (!condition) {} at the top because I see it as 'bailing out' of the function if conditions are not met.
- michaelmior 10y agoIf I'm doing an early return, I usually don't put the rest of the function inside the else case since I feel it creates an unnecessary level of indentation.