Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to do optional function parameters in JavaScript? [duplicate]

I've always handled optional parameters in JavaScript like this:

function myFunc(requiredArg, optionalArg){   optionalArg = optionalArg || 'defaultValue';    // Do stuff } 

Is there a better way to do it?

Are there any cases where using || like that is going to fail?

like image 465
Mark Biek Avatar asked Sep 29 '08 14:09

Mark Biek


People also ask

Are optional parameters bad practice?

The thing with optional parameters is, they are BAD because they are unintuitive - meaning they do NOT behave the way you would expect it. Here's why: They break ABI compatibility ! so you can change the default-arguments at one place.

Can JavaScript functions have optional parameters?

To declare optional function parameters in JavaScript, there are two approaches: Using the Logical OR operator ('||'): In this approach, the optional parameter is Logically ORed with the default value within the body of the function. Note: The optional parameters should always come at the end on the parameter list.

How do you pass optional arguments in JavaScript?

Using the Logical OR operator ('||') In this method, the optional parameter is "Logically ORed" with the default value within the body of the function. In the example below, if the value of b is undefined, 2 is passed instead.

Are parameters always optional in JavaScript?

In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value. This is where default parameters can help.


1 Answers

Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative

if (typeof optionalArg === 'undefined') { optionalArg = 'default'; } 

Or an alternative idiom:

optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg; 

Use whichever idiom communicates the intent best to you!

like image 97
Paul Dixon Avatar answered Sep 20 '22 18:09

Paul Dixon