JavaScript Tips

Summary: Write cleaner, safer JavaScript for React apps by passing destructured options objects, choosing TypeScript for long-lived code, updating objects immutably, and preferring declarative array transformations.

React is a JavaScript library.

The better JavaScript code you write, the chances are - the better React code you will write as well.

This is a collection of practical JavaScript tips that will help you write cleaner, more readable, and less bug-prone code.

1. Pass an options object for function parameters

Instead of passing three or more positional arguments whose order is easy to mix up, accept a single destructured object parameter. Read the full tip on how to declare function parameters in JavaScript.

2. Whenever possible, write TypeScript

If you have a choice to write your code with JavaScript or TypeScript - choose TypeScript. Catching prop mismatches, undefined properties, and invalid function arguments at compile time is a worthwhile investment for any codebase you expect to maintain for longer than a week.

3. Spread objects before overriding properties

When updating state immutably in React, always put ...existingObject before the property you are updating. Placing the spread last can silently overwrite your update. See the exact bug and fix in Updating JavaScript Object Property.

4. Prefer const by default

Declare bindings with const unless you genuinely need to reassign the variable later, in which case use let. Using const signals intent to readers and prevents accidental reassignment bugs.

5. Use map, filter, and find instead of imperative loops

In React components, declarative array methods keep data transformations concise and side-effect free. For example, combine .filter() and .map() when rendering lists in JSX without mutating intermediate arrays.

6. Return early to reduce nesting

Validate edge cases and error states at the top of a function and return early instead of wrapping the happy path in nested if / else blocks. Shallow functions are far easier to read, test, and refactor.