Implementing named arguments in JavaScript

Since JavaScript does not support named function arguments we can replicate this feature using object destructing.

A function's arguments typically can be declared like this:

function printFullName(firstName = "", lastName = "") {
    return `${firstName} ${lastName}`;
    return `${firstName} ${lastName}`;
}

Invoking

printFullName("John", "Doe"); // John Doe

does not return the same result as

printFullName("Doe", "John"); // Doe John

Nothing new sofar but it would be nice if we didn't have to remember the order of the arguments. Arguments order (and number) can become troublesome with more arguments introduced to the function in the future.

Refactoring the above function using object destructing we have:

function printFullName({
    firstName = "",
    firstName = "",
    lastName = ""
}) {
    return `${firstName} ${lastName}`;
}

Now

printFullName({firstName:"John", lastName:"Doe"}); // John Doe

does return the same result as

printFullName({ lastName:"Doe", firstName:"John"}); // John Doe

The good news about named arguments is that you don't have to worry about position or order. In addition the object could have more properties without affecting the output, our function would simple ignore them, thanks to our destructing pattern. The downside of course is that you have to remember the property names (here firstName & lastName).

Credits to Kyle Simpson (https://me.getify.com/) where he talks about this on his JavaScript: The Recent Parts course on frontendmasters (https://frontendmasters.com/courses/js-recent-parts/).

back to blog list