Code Renaissance is about building great teams and great software. By exploring best practices, team interactions, design, testing and related skills Code Renaissance strives to help you create the team and codebase that you've always wanted.

Named Function Expressions in JQuery & Knockout JS

Recently I was working with JQuery & Knockout in javascript and got a long running script error so I broke out the profiler to see what was wrong. Unfortunately both JQuery and Knockout code take in a lot of anonymous functions so looking at the profiler and the stack wasn't especially useful. To make the debugger and profiler more more useful I added a name to the function expression that I suspected was causing the problem similar to this:

//Changed form this:
viewModel.FooBar = ko.dependentObservable({
  read: function(){ //Note the anonymous function expression
     return this.foo() && this.bar();
  },
  owner: viewModel
});

//To this:
viewModel.FooBar = ko.dependentObservable({
  read: function readFooBar (){ //Note the name readFooBar 
     return this.foo() && this.bar();
  },
  owner: viewModel
});

These are called named function expressions (NFE's) and they can be seen in both the profiler and the call stack. As it turns out the function that I was troubleshooting didn't have a problem after all. Later the same trick allowed me to verify the real problem was in a custom binding that I had written.

Using named function expressions hasn't been common up till now because there were issues in IE8 and lower, however these issues are easily avoided by 1)giving all named function expressions unique names withing their enclosing scope and 2)NEVER referencing the NFE name in your code (IE9 and other major browsers don't allow you to do this anyway). By following these rules and making this small investment in your code you can earn huge dividends when debugging and profiling.

0 - What do you think?: