Tuesday, September 17, 2013

Javascript Named Function Expressions

BLUF: unless you are working in a controlled environment (intranet) where supported browsers only expose the identity of Named Function Expressions to the inner scope of the function (for recursive calls) they should be avoided.

In reading Test Driven Javascript Development there was discussion around using named functions to improve debugging. To provide some context lets look at this example.
Which produces the following stack trace

Those anonymous functions are hard to track down.

If we use named function expressions instead, then we can improve this stack trace.






Only problem is now we have to deal with browser quirks associated with named function expressions.

Here are a couple of great reads on the topic. 1, 2

Ideally the name would only be available to the inner scope (for the purpose of calling itself recursively) and then the rest of the issues would go away. Until then the issues outweigh the benefits. Fortunately Function Declarations will give us the same debugging benefit and won't create a new function every call.

This is hard to follow, though not significantly harder to read than before. To fix that I would recommend using promises (off topic).

The biggest issue is actually not apparent in the example, and that is that the scope context has changed. While our closure used to have access to parameters of our parent function,  it no longer does (in other words, Third could access variables from First and Second.

The simplest recommendation - and that from the books author, is to use a function declaration inside the closure.

Another option albeit off topic is to pass those variables into the function making them more explicit. Again this is where promises can help as each function can add / modify the model. (Or return different objects, etc.)



In summary, unless you are working in a controlled environment (intranet) where supported browsers only expose the identity of Named Function Expressions to the inner scope of the function (for recursive calls) they should be avoided.  

No comments:

Post a Comment