Search code examples
javascriptfunctionjavascript-objectsdestructuring

setting unset properties as default properties in a function?


I'm pretty new to JS and i'm trying to learn some basics in functions.
I'm facing a problem, I've created a function like this:

function someName (element, settings={i:"#1d252c", i2:"#fff"}) {
    .......
}

If i call the function as someName(element). i and i2 retain their values, however

If i call it like someName(element,{i:"#3acbda"}), the value of i does change however the value of i2 is undefined,

So how do i assign the default value to a property when the settings object is no longer the default value.
So when i assign settings with only i, i2 is just the default value "#fff" and not undefined.


Solution

  • You could use the Object spread operator ... to enrich your options with default settings

    function someName(element, options){
        const settings = {i:"#aaa", i2:"#fff", ...options};
        console.log(settings)
    }
    
    // let's test
    someName(null, {i:"#000"});

    which is my preferred. Alternatively you could also use a third argument:

    function someName(element, options, settings={i:"#aaa", i2:"#fff", ...options}){
        console.log(settings)
    }
    
    // let's test
    someName(null, {i:"#000"});

    In case you don't want to, or find clumbersome to always have to use the settings Object reference (like settings.i, settings.i2 etc), you can use Object unpacking - and go directly for the propertyName:

    function someName(element, options ){
        const {i="#aaa", i2="#fff"} = options; 
        console.log( i, i2 );
    }
    
    // let's test
    someName(null, {i:"#000"});