JavaScript equivalent of jQuery's extend method

To get the result in your code, you would do:

function extend(a, b){
    for(var key in b)
        if(b.hasOwnProperty(key))
            a[key] = b[key];
    return a;
}

Keep in mind that the way you used extend there will modify the default object. If you don't want that, use

$.extend({}, default, config)

A more robust solution that mimics jQuery's functionality would be as follows:

function extend(){
    for(var i=1; i<arguments.length; i++)
        for(var key in arguments[i])
            if(arguments[i].hasOwnProperty(key))
                arguments[0][key] = arguments[i][key];
    return arguments[0];
}

You can use the ECMA 2018 spread operator in object literals...

var config = {key1: value1};
var default = {key1: default1, key2: default2, key 3: default 3};

var settings = {...default, ...config}

//resulting properties of settings:
settings = {key1: value1, key2: default2, key 3: default 3};

BabelJS support for older browsers


You can use Object.assign.

var defaults = {key1: "default1", key2: "default2", key3: "defaults3"};
var config = {key1: "value1"};

var settings = Object.assign({}, defaults, config); // values in config override values in defaults
console.log(settings); // Object {key1: "value1", key2: "default2", key3: "defaults3"}

It copies the values of all enumerable own properties from one or more source objects to a target object and returns the target object.

Object.assign(target, ...sources)

It works in all desktop browsers except IE (but including Edge). It has mitigated mobile support.

See for yourself here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

About deep copy

However, Object.assign does not have the deep option that jQuery's extend method have.

Note: you can generally use JSON for a similar effect though

var config = {key1: "value1"};
    var defaults = {key1: "default1", key2: "default2", keyDeep: {
        kd1: "default3",
        kd2: "default4"
    }};
    var settings = JSON.parse(JSON.stringify(Object.assign({}, defaults, config))); 
    console.log(settings.keyDeep); // Object {kd1: "default3", kd2: "default4"}