Skip to main content
Beta: Front-End Checklist is currently in beta. Some issues are still being fixed. Thanks for your patience.

Use modern array and object methods

Use ES2015+ array methods (map, filter, reduce, find, flatMap) and object methods (Object.entries, Object.fromEntries, structuredClone) for cleaner, more expressive code.

Utilities
Quick take
Typical fix time 15 min
  • Use map() to transform arrays, filter() to select items, reduce() for aggregation
  • Use find() and findIndex() instead of manual loops with break
  • Use Object.entries() and Object.fromEntries() to transform objects
  • Use structuredClone() for deep copying instead of JSON.parse(JSON.stringify())
Why it matters: Modern array and object methods produce code that directly expresses intent — a filter() call self-documents that you're selecting items. Manual for loops obscure the purpose behind implementation details. These methods are also well-optimized by JavaScript engines and support chaining for concise data transformations.

Rule Details

Modern JavaScript provides expressive methods for working with arrays and objects that replace verbose loops with declarative transformations.

Code Example

const users = [
  { id: 1, name: 'Alice', age: 32, active: true },
  { id: 2, name: 'Bob', age: 17, active: false },
  { id: 3, name: 'Carol', age: 25, active: true }
]
 
// map() — transform every element
const names = users.map(u => u.name)
// ['Alice', 'Bob', 'Carol']
 
// filter() — select matching elements
const adults = users.filter(u => u.age >= 18)
// [Alice, Carol]
 
// find() — first matching element
const alice = users.find(u => u.name === 'Alice')
 
// findIndex() — index of first match
const bobIndex = users.findIndex(u => u.id === 2)
 
// some() / every() — boolean checks
const hasMinors = users.some(u => u.age < 18)    // true
const allActive = users.every(u => u.active)      // false

Why It Matters

Modern array and object methods produce code that directly expresses intent — a filter() call self-documents that you're selecting items. Manual for loops obscure the purpose behind implementation details. These methods are also well-optimized by JavaScript engines and support chaining for concise data transformations.

Aggregation with reduce()

// Sum a property
const totalAge = users.reduce((sum, u) => sum + u.age, 0)
 
// Group by a property
const byActive = users.reduce((groups, user) => {
  const key = user.active ? 'active' : 'inactive'
  return { ...groups, [key]: [...(groups[key] ?? []), user] }
}, {})

flatMap() for Map + Flatten

const orders = [
  { id: 1, items: ['shirt', 'pants'] },
  { id: 2, items: ['shoes'] },
  { id: 3, items: ['jacket', 'scarf', 'gloves'] }
]
 
// Get all items across all orders (flat)
const allItems = orders.flatMap(order => order.items)
// ['shirt', 'pants', 'shoes', 'jacket', 'scarf', 'gloves']

Object Methods

const prices = { apple: 1.20, banana: 0.50, cherry: 3.00 }
 
// Object.entries() — iterate as [key, value] pairs
Object.entries(prices).forEach(([fruit, price]) => {
  console.log(`${fruit}: $${price}`)
})
 
// Transform an object (entries → map → fromEntries)
const discounted = Object.fromEntries(
  Object.entries(prices).map(([k, v]) => [k, v * 0.9])
)
 
// Object.keys() and Object.values()
const fruits = Object.keys(prices)
const amounts = Object.values(prices)

Deep Cloning

// ❌ Shallow clone — nested objects still shared
const copy = { ...original }
 
// ❌ Brittle hack for deep clone
const deep = JSON.parse(JSON.stringify(original)) // loses Date, undefined, functions
 
// ✅ Modern deep clone
const deep = structuredClone(original) // Handles Date, Map, Set, circular refs

Array from Iterables

// Convert NodeList, Set, arguments to arrays
const elements = Array.from(document.querySelectorAll('.item'))
const unique = Array.from(new Set([1, 2, 2, 3, 3]))
const range = Array.from({ length: 5 }, (_, i) => i + 1) // [1, 2, 3, 4, 5]

Verification

  1. Verify the behavior in the browser after the code change, not only in static analysis.
  2. Inspect DevTools Network or Performance panels when the rule affects loading or execution order.
  3. Test the primary user flow and one edge case triggered by the changed script path.
  4. Confirm the code still behaves correctly when the feature is delayed, lazy-loaded, or fails.

Use with AI

Copy these prompts to use with your AI assistant, or install the MCP server to use directly from Claude, Cursor, or Windsurf.

Check

Verify implementation

Find loops in this file that could be replaced with modern array methods like map, filter, reduce, find, or flatMap.

Fix

Auto-fix issues

Replace manual for/while loops with appropriate array methods to make the code more declarative.

Explain

Learn more

Explain map, filter, reduce, find, flatMap, and Object.entries with practical examples.

Review

Code review

Review scripts, client components, and browser execution paths related to Use modern array and object methods. Flag exact imports, event handlers, runtime side effects, or blocking operations that violate the rule, and state how the change should be verified in the browser.

Sources

References used to support the guidance in this rule.

Further Reading

Tools and supplementary material for exploring the topic in more depth.

MDN Array methods referencedeveloper.mozilla.orgTool

Rules that often go hand-in-hand with this one.

Prefer immutable data patterns

Use spread operators, Object.assign, and array methods that return new values instead of mutating objects and arrays in place, to make data flow predictable and debugging easier.

JavaScript
Avoid implicit type coercion

Use strict equality (===), explicit type conversion, and Number/String/Boolean constructors to avoid JavaScript's implicit type coercion producing unexpected results.

JavaScript
Validate external data at runtime with a schema library

Use Zod or Valibot to validate data from API responses, form inputs, localStorage, and environment variables — TypeScript types are erased at runtime and cannot protect against unexpected shapes.

JavaScript
Never use eval() or unsafe dynamic code execution

Avoid eval(), new Function(), setTimeout/setInterval with string arguments, and innerHTML with untrusted content — they execute arbitrary code and create critical XSS vulnerabilities.

JavaScript

Was this rule helpful?

Your feedback helps improve rule quality. This stays internal for now.

Loading feedback...
0 / 385