Skip to content

About the author of Daydream Drift

Tomasz Niezgoda (LinkedIn/tomaszniezgoda & GitHub/tniezg) is the author of this blog. It contains original content written with care.

Please link back to this website when referencing any of the materials.

Author:

Modern Configuration Management In JS Libraries

Published

A very common pattern in JavaScript is for constructor functions to accept a single object with all the custom configuration (function Gallery(customOptions){...}). This object can be mapped onto a set of defaults within the constructor to provide a complete configuration, without any undefined properties. It's also easy to extend in the future with new keys while preserving support for the old ones. There are a lot of similar implementations in many external libraries of code that merges default configuration values with custom ones, such as jQuery or lodash. Now, though, there's a native solution - Object.assign. It works the same way:

function Gallery(customOptions){
	const defaults = {
		auto: false,
		init: true,
		element: null
	};
	const options = Object.assign({}, defaults, customOptions);

	if(typeof options.element !== 'Object'){
		// ...
	}
	// ...
}

So for this common task external libraries probably won't have to be used anymore. Maybe the only exception I'd care about is IE11, which doesn't and probably never will support assign but which still has a significant browser market share in 2017. For IE, either ignore it as a target for your project as its popularity will continue to dwindle, use a polyfill for specifically adding the function to the environment or rely on preprocessors like Babel to standardize the whole environment, including adding Object.assign where it's normally unavailable.