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

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!

Leave a Comment