javascript tutorial - [Solved-5 Solutions] Is there a better way to do optional function parameters in javascript ? - javascript - java script - javascript array
Problem:
I've always handled optional parameters in Javascript like this:
Is there a better way to do it? Are there any cases where using || like that is going to fail?
Solution 1:
Our logic fails if optionalArg is passed, but evaluates as false - try this as an alternative
Or an alternative idiom:
Use whichever idiom communicates the intent best to you!
Solution 2:
We find this to be the simplest, most readable way:
Paul Dixon's answer (in my humble opinion) is less readable than this, but it comes down to preference. insin's answer is much more advanced, but much more useful for big functions! EDIT 11/17/2013 9:33pm: I've created a package for Node.js that makes it easier to "overload" functions (methods) called parametric .
Solution 3:
In ECMAScript 2015 (aka "ES6") we can declare default argument values in the function declaration:
More about them in this article on MDN (despite the article title, they're called "arguments," not "parameters," in JavaScript). This is currently only supported by Firefox, but as the standard has been completed, expect support to improve rapidly.
Solution 4:
If we need to chuck a literal NULL in, then we could have some issues. Apart from that, no, we think you're probably on the right track. The other method some people choose is taking an assoc array of variables iterating through the argument list. It looks a bit neater but we imagine it's a little (very little) bit more process/memory intensive.
Solution 5:
We can use some different schemes for that, I've always tested for arguments.length:
-- doing so, it can't possibly fail, but we don't know if our way has any chance of failing, just now we can't think up a scenario, where it actually would fail ...