Course contentsShow
← JavaScript
Lesson 857 of 2,72320. Array Iteration and TransformationFree lesson

Order Matters in Chains

How the order of map and filter affects performance and results in method chains.

Order Matters in Chains

You'll learn why the sequence of map and filter in method chains affects both performance and results.

When you chain array methods like map and filter, the order you apply them can dramatically change what happens. Each method processes the array it receives, then passes its result to the next method in the chain.

Performance Impact

Consider filtering first vs mapping first:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Filter THEN map: processes fewer elements in map
const result1 = numbers
  .filter(n => n > 5)     // Returns [6, 7, 8, 9, 10] - 5 elements
  .map(n => n * 2);       // Processes only 5 elements

// Map THEN filter: processes all elements in map
const result2 = numbers
  .map(n => n * 2)        // Processes all 10 elements
  .filter(n => n > 10);   // Returns [12, 14, 16, 18, 20]

Both produce the same final result [12, 14, 16, 18, 20], but result1 is more efficient because map only processes 5 elements instead of 10.

Result Changes

Sometimes order changes the outcome entirely:

const words = ['hi', 'hello', 'hey', 'greetings'];

// Filter by original length, then uppercase
const a = words
  .filter(w => w.length > 3)  // ['hello', 'greetings']
  .map(w => w.toUpperCase()); // ['HELLO', 'GREETINGS']

// Uppercase first, then filter (still works on transformed values)
const b = words
  .map(w => w.toUpperCase())  // ['HI', 'HELLO', 'HEY', 'GREETINGS']
  .filter(w => w.length > 3); // ['HELLO', 'GREETINGS']

Think of it like an assembly line: the order of stations determines what gets processed and how much work each station does.

Key Takeaway: Filter before map when possible to reduce the number of transformations, and always consider whether order affects your final results.