There are native ways of parsing options for methods however in lodash there is a quick convenience method that can be used to handle this process which is called the _.defaults object method. In this post I will be showing some quick use case examples of the _.defaults method, as well as some vanilla js alternatives when it comes to option parsing and javaScipt methods.
So one use case example is when making a constructor function, and I want to have an options object that can be passed to the method. This options object contains properties that are to be set as the initial state of an instance of the constructor when used with the new keyword. The _.defaults method can be used along with _.merge to make quick work of this.
So say you have a constructor method that creates a simple Box Class object. You want to make it so that there are default values for the width, height, and x an y properties of the Box Class instance. The lodash defaults method can be used to do just this with an options object that is used for the constructor. Just pass the options object as the first argument to the defaults method, and then as the second argument an object of default values for each property.
This approach works fine as long as all properties given in the options object can be set to the instance of the Constructor, else I might want this options object to be a separate argument, or have other properties that are just used once during construction handled in another object.
The same constructor could be made without lodash using ternary operators.
This might work fine if I just have a few properties like in this example, but if the constructor gets a little complex, it is nice to have a better solution for handing this.
The lodash _.defaults method one of the many methods in lodash that makes it a great utility library. This is something that comes up a lot when making projects. One way of other I just work through it, but if lodash is part of the stack it is nice to know that I have this available as an option. If you enjoyed this post you might want to check out my main post on lodash in general.