Similarly within a method, avoid switching between if statements and switch statements and back:
if (x === y) {
return 'x';
}
switch (x) {
case z:
...
}
if (x ...
This is better written with pure if statements.
Continuing this thought process, don't switch between method short circuiting and "The One Return" (with one exception: arg checks):
if (x) { return a; }
if (y) { return b; }
if (z) { r = ... }
if (!r && t) { r = ... }
...
return r || ...;
}
In general, logic that changes in style is much harder to read than logic that remains stylistically constant.
- Pull constants out
If a variable doesn't change within a function or between runs of a function, then it is not a variable with respect to that function. Thus it doesn't belong there (except at the root level).
Use the right method for the job
Instead of Use .attr('data-x') .data('x') if (x) { $a.show() } else { $a.hide() } $a.toggle(x) x ? $a.addClass('a') : $a.removeClass('a') $a.toggleClass('a', x)