Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

Lodash _.defaults() Object Method

Posted in lodash Tutorial
Updated on Oct 30, 2024
By Mari Selvan
👁️ 57 - Views
⏳ 4 mins
💬 1 Comment
Lodash _.defaults() Object Method

Photo Credit to CodeToFun

🙋 Introduction

In the landscape of JavaScript development, effective handling of objects is fundamental. Lodash, a powerful utility library, offers a range of functions to streamline object manipulation. Among these functions is the _.defaults() method, a versatile tool for merging default values into an object.

This method enhances code flexibility and maintainability, making it an invaluable asset for developers dealing with complex object structures.

🧠 Understanding _.defaults() Method

The _.defaults() method in Lodash is designed to populate undefined properties in an object with corresponding values from a defaults object. This ensures that the target object contains all the necessary properties, with the option to provide default values for missing ones.

💡 Syntax

The syntax for the _.defaults() method is straightforward:

syntax.js
Copied
Copy To Clipboard
_.defaults(object, [defaults])
  • object: The target object to populate.
  • defaults: The object with default values.

📝 Example

Let's dive into a simple example to illustrate the usage of the _.defaults() method:

example.js
Copied
Copy To Clipboard
const _ = require('lodash');

const targetObject = { a: 1, b: 2 };
const defaultsObject = { b: 3, c: 4 };

const mergedObject = _.defaults(targetObject, defaultsObject);

console.log(mergedObject);
// Output: { a: 1, b: 2, c: 4 }

In this example, the targetObject is merged with defaultsObject using _.defaults(), resulting in a new object with default values applied to undefined properties.

🏆 Best Practices

When working with the _.defaults() method, consider the following best practices:

  1. Understand Object Structure:

    Before applying _.defaults(), have a clear understanding of the structure of both the target object and the defaults object. This ensures accurate merging of properties.

    example.js
    Copied
    Copy To Clipboard
    const userSettings = { username: 'JohnDoe', theme: 'light' };
    const defaultSettings = { theme: 'dark', language: 'en' };
    
    const mergedSettings = _.defaults(userSettings, defaultSettings);
    
    console.log(mergedSettings);
    // Output: { username: 'JohnDoe', theme: 'light', language: 'en' }
  2. Avoid Mutating Original Object:

    If you want to keep the original object unaltered, create a new object and apply _.defaults() to it. This helps maintain immutability in your code.

    example.js
    Copied
    Copy To Clipboard
    const originalObject = { key1: 'value1' };
    const defaults = { key2: 'value2' };
    
    const mergedObject = _.defaults({}, originalObject, defaults);
    
    console.log(mergedObject);
    // Output: { key1: 'value1', key2: 'value2' }
    console.log(originalObject);
    // Output: { key1: 'value1' }
  3. Combine with ES6 Spread Operator:

    For a more modern approach, consider using the ES6 spread operator to achieve a similar result. This provides a concise syntax for merging objects.

    example.js
    Copied
    Copy To Clipboard
    const targetObject = { a: 1, b: 2 };
    const defaultsObject = { b: 3, c: 4 };
    
    const mergedObject = { ...defaultsObject, ...targetObject };
    
    console.log(mergedObject);
    // Output: { a: 1, b: 2, c: 4 }

📚 Use Cases

  1. Configurable Options:

    _.defaults() is particularly useful when working with configurable options. It allows developers to set default values for various options while providing users the flexibility to customize settings.

    example.js
    Copied
    Copy To Clipboard
    const userOptions = { theme: 'dark', fontSize: 16 };
    const defaultOptions = { theme: 'light', fontSize: 14, language: 'en' };
    
    const finalOptions = _.defaults(userOptions, defaultOptions);
    
    console.log(finalOptions);
    // Output: { theme: 'dark', fontSize: 16, language: 'en' }
  2. Merging User Preferences:

    When dealing with user preferences or settings, _.defaults() simplifies the process of merging user-provided values with default configurations.

    example.js
    Copied
    Copy To Clipboard
    const userPreferences = { showNotifications: true, darkMode: true };
    const defaultPreferences = { showNotifications: false, darkMode: false, fontSize: 14 };
    
    const mergedPreferences = _.defaults(userPreferences, defaultPreferences);
    
    console.log(mergedPreferences);
    // Output: { showNotifications: true, darkMode: true, fontSize: 14 }
  3. API Request Configuration:

    In scenarios where you need to configure API requests, _.defaults() can be used to merge user-defined headers or parameters with default values.

    example.js
    Copied
    Copy To Clipboard
    const userHeaders = { Authorization: 'Bearer Token123' };
    const defaultHeaders = { ContentType: 'application/json', Timeout: 5000 };
    
    const mergedHeaders = _.defaults(userHeaders, defaultHeaders);
    
    console.log(mergedHeaders);
    // Output: { Authorization: 'Bearer Token123', ContentType: 'application/json', Timeout: 5000 }

🎉 Conclusion

The _.defaults() method in Lodash provides an efficient way to merge default values into objects, offering enhanced flexibility and maintainability in your JavaScript code. Whether you're configuring options, managing preferences, or handling API requests, _.defaults() is a valuable tool for ensuring that your objects have the necessary properties with sensible default values.

By adhering to best practices and exploring diverse use cases, you can harness the full potential of the _.defaults() method in your Lodash projects.

👨‍💻 Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
👋 Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy