JavaScript – Creating Default Arguments
I ran into an interesting quirk with JavaScript yesterday, one I’m surprised I hadn’t noticed before. JavaScript does not allow you to give arguments default values when defining functions. So after a bit of tinkering, I came up with a solution.
function lorum(x, y) {
if(typeof(x) == "undefined") {
x = 100;
}
if(typeof(y) == "undefined") {
y = 500;
}
// ...
}
Of course you could use a ternary operator if you prefer, however I know I’m not alone when I say that I do not like them. In any case, here’s an example using them:
function ipsum(i, j) {
i = typeof(i) == "undefined" ? 100 : i;
j = typeof(j) == "undefined" ? 500 : j;
// ...
}
Despite its reduced code space, I prefer not to use them as they can be confusing at first glance. But to each his own.
fettesps

