Adding Optional Parameters to a Javascript Function

Here's a quick pattern tip on setting optional parameter values in JavaScript.

Using destructuring, you can pass an empty object as your default parameter value. Then using destructuring again, you can set named variables as any values that get passed into your options parameter.

function newsArticle(options: newsArticleOptions) {
    const {
        showHeadline = true,
        showDate = true,
        articleType = "World"
    } = options;
}

// Use like this
newsArticle({ articleType: "Tech" });

// Of course, don't write JavaScript without TypeScript
interface newsArticleOptions {
    showHeadline?: boolean
    showDate?: boolean
    articleType?: articleType
}

type articleType = "Tech" | "World" | "Sports"

One Last Thing...

If you have a question or see a mistake, please comment below.

If you found this post helpful, please share it with others. It's the best thanks I can ask for & it gives me momentum to keep writing!

Matt Ferderer
Software Developer focused on making great user experiences. I enjoy learning, sharing & helping others make amazing things.
Let's Connect