HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
functionbetteroptionalwayparametersjavascriptthere

Problem

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?

Solution

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!

Code Snippets

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

Context

Stack Overflow Q#148901, score: 1104

Revisions (0)

No revisions yet.