Yesterday I wrote about how you’re supposed to be able to process conditional function parameters in JavaScript:
1 2 3 4 5 |
function addTransformToList(sElement,tDuration,trans,tAdjustment,mMethod) { var tAdjustment = typeof tAdjustment !== "undefined" tAdjustment : ""; var mMethod = typeof mMethod !== "undefined" mMethod : "linear"; ... } |
The teeeensy little problem is that neither browsers nor syntax checkers in certain development tools (WebStorm, in my case, I used it to check my code when editing in Notepad++ and running the Firefox debugger wasn’t getting me anywhere) will accept this configuration. The individual pieces are all fine, they just don’t actually work when you use them together.
Therefore I rewrote the code longhand and, voilà, it worked!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function addTransformToList(sElement,tDuration,trans,imMethod,itAdjustment) { var mMethod; if ((typeof imMethod) === "undefined") { mMethod = "linear"; } else { mMethod = imMethod; } //interpreter really chokes on this! //var mMethod = (typeof mMethod !== "undefined") mMethod : "linear"; //interpreter halfway accepts this, but only halfway //var mMethod = (typeof mMethod === "undefined") "linear" : mMethod; var tAdjustment; if ((typeof itAdjustment) === "undefined") { tAdjustment = ""; } else { tAdjustment = itAdjustment; } //var tAdjustment = ((typeof tAdjustment) === "undefined") "" : tAdjustment; |
Obviously one should not believe everything you read on the internet–especially if you only read the first part of it. If you read just a little bit further down in the link you see that the following should work, at least in some browsers:
1 2 3 |
function addTransformToList(sElement,tDuration,trans,mMethod = "linear",tAdjustment = "") { ... } |
I can confirm that this works, at least in Firefox.
Addendum, February 17, 2017: This a) would have been better if I’d actually put the link data in the link (I’m guessing it’d be real hard to find again) and b) I’ve since learned that this behavior is one of the differences between ES5 and ES6, which I didn’t pick up on at the time. The version of WebStorm I was using was not processing ES6 constructs.