A slightly more verbose, yet hardy syntax would go like this:
function foo(arg1, arg2){
arg1 = arg1 === undefined ? "foo" : arg1;
arg2 = arg2 === undefined ? "bar" : arg2;
}
This would catch the intended behavior, which is to fill a parameter when it is not supplied at all.In fact you're just compacting an if:
if (arg1 == null) { // check for both `undefined` and `null`
arg1 = 'default';
}
// compacted to:
arg1 = arg1 == null ? 'default' : arg1;
The difference is that you're always doing an assignement, even if unnecessary. (arg1 == null) && (arg1 = 'default');I could see, using the if statement form, that you might have a programmer decide to compact it and drop the brackets - and then you might fall in the trap where somebody thinks they're in an if block when they're really not. Happens pretty often.
In addition, I don't know if you really would want to check for null. I usually just check for undefined, which would be the absence of any provided value (as opposed to a provided value that just happens to be null). Of course, it depends on the app.
In addition, I really don't like using short-circuited boolean ops for assignment. The style is grating to me - it's not immediately obvious what it's really doing. To each his own.
EDIT: Created a simple jsperf test. Difference is about 6.8%, but we're talking hundreds of millions of ops/s. Not the kind of stuff that matters outside of raw benches.
myfn('a',undefined,'b');