lodash
lodash is a JavaScript utility library providing consistent, cross-environment, performance-optimized, and modular utilities for common programming tasks. It simplifies working with arrays, objects, numbers, strings, and functions, offering a wide range of helpers for iteration, manipulation, and type checking. The current stable version is 4.18.1, with frequent updates for bug fixes and security patches, typically released as minor or patch versions.
Common errors
-
ReferenceError: <variable name> is not defined
cause Internal dependency mapping issue in `_.template` or `_.fromPairs` functions when imported individually or from modular builds in versions prior to 4.18.1.fixUpgrade `lodash` to version `4.18.1` or higher. -
TypeError: require is not a function
cause Attempting to use CommonJS `require` syntax within an ES Module (ESM) file context.fixRefactor `const _ = require('lodash');` to `import _ from 'lodash';` for ESM compatibility. -
SyntaxError: Cannot use import statement outside a module
cause Attempting to use ES Module `import` syntax within a CommonJS (CJS) file context or a project not configured for ESM.fixRefactor `import _ from 'lodash';` to `const _ = require('lodash');` for CJS compatibility, or configure your project to use ES Modules (e.g., by setting `"type": "module"` in `package.json`).
Warnings
- breaking lodash v4.0.0 introduced significant back-compatible breaking changes to align with semantic versioning practices.
- breaking lodash v3.0.0 included several back-compatible breaking changes as part of a major cleanup and refactoring.
- gotcha A prototype pollution vulnerability via `_.unset` and `_.omit` path traversal was fixed.
- gotcha A `ReferenceError` could occur when using `_.template` or `_.fromPairs` from modular builds due to internal dependency issues.
- gotcha Lodash functionality in the Node.js REPL may be inconsistent or require a polyfill for Node.js versions prior to 6.
Install
-
npm install lodash -
yarn add lodash -
pnpm add lodash
Imports
- _
const _ = require('lodash');import _ from 'lodash';
Quickstart
import _ from 'lodash';
const users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false }
];
const activeUsers = _.filter(users, function(o) { return o.active; });
console.log(activeUsers);
// Expected output: [ { user: 'barney', age: 36, active: true } ]