News for hackers. Stuff that matters.
Re:Default Parameters in JavaScript by STRML on Tuesday March 19, 2013 @12:03PM (#5401687)
The assignment is hardly a performance concern in modern javascript. I imagine if we set up a jsperf test case we would find the difference negligible and the ops/s in the 10s of millions range. This is not the kind of thing that slows down JS apps.

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.

http://jsperf.com/ternary-vs-if-for-default-args

Re:Default Parameters in JavaScript by yuchi on Tuesday March 19, 2013 @01:20PM (#5402225)
I'm not talking about single occurence of the "bad" pattern. If you multiple it to the occurence in a whole code base... well you get the point. That's why underscore and coffee-script treat default assignement that way.
Re:Default Parameters in JavaScript by STRML on Thursday March 21, 2013 @01:09PM (#5416844)
Interestingly, in JSPerf, sometimes the ternary pattern is actually faster than the if statement. Must be something V8 is doing.
Re:Default Parameters in JavaScript by leeoniya on Tuesday March 19, 2013 @12:11PM (#5401737)
you may have to check for null if you want to use a default arg2 while providing an explicit arg3. i guess you can always do:

    myfn('a',undefined,'b');
Re:Default Parameters in JavaScript by STRML on Tuesday March 19, 2013 @12:16PM (#5401765)
Yeah. You see that sometimes in modern JS, e.g. when pretty-printing JSON:

  JSON.parse(object, undefined, 2);