Explain Codes LogoExplain Codes Logo

How can I declare optional function parameters in JavaScript?

javascript
functions
promises
callbacks
Alex KataevbyAlex Kataev·Dec 20, 2024
TLDR

Handle optional parameters in JavaScript through default parameters. You can set defaults right in the function signature:

function example(param = 'default') { console.log(param); } example(); // "default", no arguments passed example('specific'); // "specific", specific argument passed

In this case, param defaults to 'default' when it's not explicit, making function calls easy and reducing logic inside the function.

ES6 default parameters

ES6 provides a sleek way to handle optional parameters by supporting default values:

// Welcome to JavaScript short-cuts ✂️ function greet(name = 'Visitor', greeting = 'Hello') { return `${greeting}, ${name}!`; }

ES6 Vs ES5 default values

ES6 only uses the default value if no argument was passed or if it's undefined. But in ES5, developers made use of || operator for default values:

// Back in my day, we used to trudge uphill in freezing temperatures... ⏳ function greet(name, greeting) { name = name || 'Visitor'; greeting = greeting || 'Hello'; return `${greeting}, ${name}!`; }

Be aware, though, that this method doesn't differentiate between null, false, 0, or '' and undefined - all are falsy values. ES6's default parameters only activate if the value is undefined.

Dealing with exceptions

ES6 does not consider null as undefined, hence, they don't trigger default parameter handling. For more robustness against falsy values, add parameter checking:

// Null Terminator 🔫 function greet(name = 'Visitor', greeting = 'Hello') { if (name === null) name = 'Visitor'; if (greeting === null) greeting = 'Hello'; return `${greeting}, ${name}!`; }

In an ES5 context, check if the value is undefined:

// Nullinator: Rise of the Falseys 🕶️ function greet(name, greeting) { name = name === undefined ? 'Visitor' : name; greeting = greeting === undefined ? 'Hello' : greeting; return `${greeting}, ${name}!`; }

Pitfalls

Mismanaged optional parameters can lead to unclear function usage or unforeseen behaviors. Overhauling functions with many optional parameters may muddle your function's purpose, especially if parameters cause side effects or require complex fiddling before use.

Use of truthiness in JS

Understanding truthy and falsy is essential when handling default parameters in pre-ES6 environments. Before the advent of default parameters, checking for undefined was mission-critical.

Check optional parameters first

It's common practice to validate optional parameters first in your function body for robustness and clarity.

Handling unknown parameters

If you don't know the number of optional parameters, the arguments object can come to rescue:

function logAllArguments() { for (var i = 0; i < arguments.length; i++) { console.log(arguments[i]); } }

References