跪拜 Guibai
← All articles
Frontend · JavaScript · Interview

10 JavaScript Tricks That Cut 30% of Your Boilerplate

By 不简说 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

These patterns replace the most common sources of silent bugs and verbose guard code in everyday JavaScript. Adopting even half of them reduces the surface area for null-reference errors, incorrect default values, and cross-realm type-check failures.

Summary

A practical collection of JavaScript techniques that shrink common boilerplate by roughly 30%. Each tip follows a pitfall-solution-explanation format drawn from real debugging sessions. The focus spans conditionals, type checking, and design patterns.

Optional chaining replaces deeply nested `&&` guards, the nullish coalescing operator `??` stops `0` and empty strings from triggering defaults, and logical assignment operators condense conditional writes into one line. For type checking, `Object.prototype.toString.call()` handles edge cases where `typeof` and `instanceof` fail, and `Array.isArray()` avoids cross-realm prototype-chain bugs.

Design pattern entries show that ES modules are already singletons, a lookup table eliminates `if/else` chains, a 30-line `EventEmitter` implements pub/sub, `Proxy` creates flexible read-only views, and function wrappers add logging without touching the original logic. Each pattern includes the specific runtime gotcha that trips people up.

Takeaways
Optional chaining `?.` short-circuits on `null`/`undefined` but not on `0`, `''`, or `false` — mixing it with `&&` logic causes subtle bugs.
The nullish coalescing operator `??` uses the default only for `null`/`undefined`, unlike `||` which also triggers on `0` and empty strings.
Logical assignment operators (`??=`, `||=`, `&&=`) combine a condition check with assignment in one expression, but `||=` overwrites falsy values like `0`.
`Object.prototype.toString.call(value)` returns precise type strings such as `'Array'`, `'Date'`, `'RegExp'`, and `'Promise'`, avoiding `typeof` and `instanceof` blind spots.
`Array.isArray()` correctly identifies arrays across iframe and Web Worker boundaries where `instanceof Array` fails due to separate prototype chains.
ES modules are naturally singletons — importing the same module multiple times returns the same reference, making manual singleton classes unnecessary.
Replacing `if/else` chains with a lookup table (strategy pattern) makes adding new cases a one-line change without touching the dispatch logic.
A minimal `EventEmitter` in roughly 30 lines handles pub/sub; the main production risk is memory leaks from listeners that are never removed.
`Proxy` can enforce read-only access with custom error messages, but it does not freeze the underlying object — direct mutations still succeed.
Function-wrapper decorators add cross-cutting concerns like logging without modifying the original function, though they lose the original function name in stack traces.
Conclusions

The list is a tour of JavaScript's post-ES2020 ergonomics: nearly every tip replaces a pre-existing verbose pattern with a language-level operator or a built-in module behavior. The underlying message is that hand-rolled boilerplate is now a smell.

Several tips highlight that newer syntax (`??`, `?.`) introduces its own gotchas when developers mentally map it onto older operators (`||`, `&&`). The transition cost is not learning the new feature but unlearning the old mental model.

The design-pattern section implicitly argues that JavaScript's module system and object literals already implement patterns that Java-style OOP requires classes for — singletons and strategies need almost no ceremony.

Concepts & terms
Optional chaining (`?.`)
A JavaScript operator that short-circuits to `undefined` when accessing a property on `null` or `undefined`, replacing chains of `&&` guards. It does not short-circuit on other falsy values like `0` or `''`.
Nullish coalescing operator (`??`)
Returns the right-hand operand only when the left-hand is `null` or `undefined`, unlike `||` which also treats `0`, `''`, and `false` as triggers for the default.
Logical assignment operators (`??=`, `||=`, `&&=`)
ES2021 operators that perform a logical check and assign the result in one step. `x ??= y` assigns `y` only if `x` is `null`/`undefined`; `x ||= y` assigns if `x` is any falsy value.
Strategy pattern (lookup table)
Replaces conditional chains with an object mapping keys to functions. Calling `strategies[key](...args)` dispatches behavior without `if/else` branching, making the logic open for extension but closed for modification.
Proxy (read-only view)
A JavaScript `Proxy` intercepts operations like `set` and `deleteProperty` on a target object. It can enforce read-only access with custom errors but does not prevent direct mutation of the underlying object.
From the discussion
Featured comments
user1841103045928

I don't know why there are posts like this every year.

不简说

Because there are graduates every year. [grin]

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗