Home > Software engineering >  Is there a way to nest simulated named parameters in Javascript?
Is there a way to nest simulated named parameters in Javascript?

Time:12-31

Background

I am creating a function that handles dom manipulation such as creating an element, adding/setting some properties on the element, and appending it to a parent. I wanted to use named parameters, but from my research I found that this feature is not built into JS. This enter image description here

Problem and Attempted Solution

As some of these parameters are required and the rest are optional, I would like to separate the optional parameters into a separate object within the function parameter object without losing the Visual Studio hint that shows which params are available. I tried to do this with:

const createElement = function createNewDomElement({
        tag,
        options: {
            parent, 
            idName, 
            className,
            innerHTML,
            href
        }
    }={}) {
    
    if (options) {
        options.forEach(item => console.log(item));
    }

}

However, when I try to access the options the same way as I was able to access the parent parameter in the first example, it says it is not defined.

Question

Is there a way to nest simulated named parameters in a way that maintains the Visual Studio Code hint showing which parameters are available?

I am also open to solutions which work, but where I lose the hint.

CodePudding user response:

You won't be able to iterate those attributes but you can access it in this way

function createElement({
        tag,
        options: {
            parent, 
            idName, 
            className,
            innerHTML,
            href
        }
    } = { options: {} }) {
    
    if (parent) {
        console.log(parent)
    }
}
  • Related