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

Software engineer who spends his time learning about building teams, project management, software architecture, C#, .NET Core, Blazor, JavaScript, TypeScript, Azure, user experience, web security, and performance.