Wednesday, January 4, 2012

Another good javascript interview question

I was debugging some Node.js code recently and found a bug that is so obvious but very easy to get that  to creep in if you are not careful enough. The following code is just a sample, not reflecting the real code that I'm working on.

The buggy version
Do you see the problem??  That could be one of the interview questions for my next candidate.  I can think of  three different ways to solve this scope issue, two of them are pretty standard, the other one is more elegant :)  Can you think of at least one?

(function() {
//...
for ( key in MyModules){
    if(MyModules.hasOwnProperty(key)){
        module = MyModules[key];
        // if you're not coming from Node.js, the code 
        // inside will get execute during runtime
        app.get(module.regEx ,function(req,res,next){
            module.router(req,res,next,module.collection); 
        });
    }
}
//...
}());

As a javascript developer, the basic minimal concepts we should know before going into an interview would be "prototype, scope and closure".  Because from those concepts, one can generate different patterns out from them.


2 comments:

  1. Hi Can you provide the elegant way of solving this? :)

    One solution I can thin of is:
    for (;;){
    (function(i){
    setTimeout(function(){

    rest of the code
    .
    .
    }, 1000*(i));
    })(i);
    }

    ReplyDelete
  2. Closures!

    (function() {

    //...

    for ( key in MyModules){
    if(MyModules.hasOwnProperty(key)){
    module = MyModules[key];
    // if you're not coming from Node.js, the code
    // inside will get execute during runtime
    app.get(module.regEx , (function (mod) {
    return function(req,res,next) {
    mod.router(req,res,next,mod.collection);
    };
    })(module));
    }
    }

    //...

    }());

    ReplyDelete