Sunday, December 30, 2018

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





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?


Answer



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!


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...