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"

Matt Ferderer

Full Stack Software Developer focused on JavaScript and C#. Love to share & help others make amazing things. Have a project you need help on? Let's talk!