About js-early-exit
A JavaScript pattern for returning as soon as the outcome is known, skipping unnecessary work. It is for developers seeking to avoid redundant iteration or expensive operations.
Key features
- 01Return as soon as a condition is met
- 02Skip subsequent processing
- 03Avoid unnecessary computation
Use cases
- 01Stop validation at the first invalid user
- 02Avoid processing every item before returning
Install
Copy the command and run it in a terminal.
$
npx skills add https:/ / github.com/ theorcdev/ 8bitcn-ui --skill js-early-exitAfter installing, type/js-early-exitin Claude Code to confirm it loaded.
Details
From the project READMEEarly Return from Functions
Return early when result is determined to skip unnecessary processing. This optimization is especially valuable when the skipped branch is frequently taken or when the deferred operation is expensive.
Incorrect (processes all items even after finding answer):
function validateUsers(users: User[]) {
let hasError = false
let errorMessage = ''
for (const user of users) {
if (!user.email) {
hasError = true
errorMessage = 'Email required'
}
if (!user.name) {
hasError = true
errorMessage = 'Name required'
}
// Continues checking all users even after error found
}
return hasError ? { valid: false, error: errorMessage } : { valid: true }
}
Correct (returns immediately on first error):
function validateUsers(users: User[]) {
for (const user of users) {
if (!user.email) {
return { valid: false, error: 'Email required' }
}
if (!user.name) {
return { valid: false, error: 'Name required' }
}
}
return { valid: true }
}
Comments
Markdown supported