Lodash flip Method Explained

The _.flip method in the Lodash JavaScript library creates a wrapper function that invokes the provided function with its arguments reversed. This article explains how _.flip alters argument sequencing, demonstrates its behavior through practical code examples, and details the scenarios where it is most effectively used in functional programming.

What _.flip Does to Argument Order

When you pass a function to Lodash's _.flip(func), it returns a new function. When this new function is called, it takes all supplied arguments and reverses their positional order before handing them to the original underlying function.

If an original function accepts arguments in the order of (a, b, c, d), calling its flipped version with those same values results in the original function receiving them as (d, c, b, a).

Code Example

const _ = require('lodash');

function listArguments(first, second, third) {
  return [first, second, third];
}

// Normal invocation
listArguments('first', 'second', 'third');
// => ['first', 'second', 'third']

// Create a flipped version of listArguments
const flippedList = _.flip(listArguments);

// Flipped invocation
flippedList('first', 'second', 'third');
// => ['third', 'second', 'first']

How It Works with Variable Arguments

The _.flip method is not restricted to fixed-arity functions. It captures all arguments provided at call time, applies an array reversal operation to them, and spreads them into the target function invocation.

const gatherAll = (...args) => args;

const flippedGather = _.flip(gatherAll);

flippedGather(1, 2, 3, 4, 5);
// => [5, 4, 3, 2, 1]

Common Use Cases

Key Characteristics