how to use the defaults function from lodash in javascript

The defaults() function in lodash helps to set default values for object properties that are not assigned yet or are assigned with undefined.

Here's an example of how to use defaults() in JavaScript with lodash:

index.tsx
const _ = require('lodash');

const defaultOptions = {
  timeout: 5000,
  maxRetries: 3,
  retryDelay: 1000
};

const userOptions = {
  timeout: 10000
};

const options = _.defaults(userOptions, defaultOptions);

console.log(options);
// Output: { timeout: 10000, maxRetries: 3, retryDelay: 1000 }
298 chars
17 lines

In this example, defaultOptions contains the default values for some options. userOptions contains some options set by the user. We apply the defaults() function to merge userOptions with defaultOptions.

As a result, options will contain all the options, with userOptions taking priority over defaultOptions. The output of the console.log() statement confirms that timeout property has been overridden with value from userOptions and all other properties have been copied from defaultOptions.

With this kind of approach, we can ensure that all required options are present in an object and avoid errors due to missing properties.

gistlibby LogSnag