Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A native JS extend() function.


var defaults = {
    number: 1,
    bool: true,
    magic: 'real',
    animal: 'whale',
    croutons: 'delicious'

var options = {
    number: 2,
    magic: 'real',
    animal: 'porpoise',
    bool: false,
    random: 42

var settings = extend(defaults, options);

// Returns: Object{animal: "porpoise", bool: false, croutons: "delicious", magic: "real", number: 2, random: 42}
* Merge defaults with user options
* @private
* @param {Object} defaults Default settings
* @param {Object} options User options
* @returns {Object} Merged values of defaults and options
var extend = function ( defaults, options ) {
var extended = {};
var prop;
for (prop in defaults) {
if (, prop)) {
extended[prop] = defaults[prop];
for (prop in options) {
if (, prop)) {
extended[prop] = options[prop];
return extended;

This comment has been minimized.

Copy link

@jimmynotjim jimmynotjim commented Apr 18, 2018

This is awesome, thanks so much for sharing it.


This comment has been minimized.

Copy link

@diniremix diniremix commented Jun 13, 2019

very useful, thanks


This comment has been minimized.

Copy link

@hyfydistro hyfydistro commented Apr 10, 2021

This is similar to Object.assign(). Is there a reason to use one over the other?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment