Lodash _.functions Method Explained

The _.functions method in the Lodash JavaScript library inspects an object and extracts an array containing the names of all its own enumerable function properties. This article explains how _.functions operates, what specific data it retrieves, how it filters object properties, and how it differs from similar Lodash methods.

What _.functions Extracts

The _.functions method (also aliased as _.methods) iterates through an object and returns an array of string keys representing properties whose values are functions.

Specifically, the method extracts:

The returned array contains the property names (keys) as strings, sorted in ascending alphabetical order, rather than the function implementations themselves.

Code Example

const _ = require('lodash');

function CustomService() {
  this.start = function() { return 'started'; };
  this.stop = function() { return 'stopped'; };
  this.status = 'active'; // Non-function property
}

// Inherited prototype method
CustomService.prototype.restart = function() { return 'restarted'; };

const service = new CustomService();

const result = _.functions(service);
console.log(result);
// Output: ['start', 'stop']

In this example, _.functions extracts ['start', 'stop']. It ignores the string property status because it is not a function, and it ignores restart because it belongs to the prototype chain rather than the instance itself.

_.functions vs. _.functionsIn

Lodash provides a companion method called _.functionsIn. The key distinction lies in inheritance:

Using _.functionsIn(service) on the previous example would yield ['restart', 'start', 'stop'].

Common Use Cases

The _.functions method is primarily used for: