Published on

Handling Nested Default Options in JavaScript

Authors

If you are working with nested objects as default options then node-defaults might be a tiny package that makes your life simpler by deeply merges the given options with the specified defaults for you.

Dependency

npm install defaults

Usage

import defaults from "defaults";

const sendEmail = (config) => {
  const defaultConfig = {
    smtpConfig: {
      host: "smtp.example.com",
      port: 587,
    },
  };
  config = defaults(config, defaultConfig);

  console.log(config);

  // your logic here ...
};

sendEmail({
  smtpConfig: {
    host: "smtp.gmail.com",
  },
});

/* Now, the "config" will be 👇

{
   smtpConfig: {
     host:"smtp.gmail.com",
     port:587 
   } 
}

*/

Happy nested config!