javascript
JavaScript style
Personal JS style rules to follow whenever touching JavaScript. All of these also apply to TypeScript — the typescript skill loads this one first.
The unifying theme: keep code flat and readable so the next reader (or you next month) can follow the happy path top-to-bottom without parsing branches in their head. These rules catch bugs that show up under refactor or reuse — the situations where dense, branchy code rots fastest.
1. Prefer early returns over else
else deepens indentation, multiplies branches, and pushes the happy path further from the function entry. In ~95% of cases an if/else rewrites cleanly as a guard with an early return — the function then reads top-to-bottom, edge cases handled and out of the way at the top, main logic flat below.
When the non-happy branch is more than a couple lines, extract it into a named function. The guard collapses to a one-liner, and naming the branch usually clarifies intent.
Wrong: