Javascript interview questions.

    1. 10 + 10 + ’10′ – result is “2010″. ’10′ + 10 + 10 = “101010″
    2. Difference between two declarations of methods.
function A(){
   this.mymethod = function(){console.log('method');}
}

and

function A(){}
A.prototype.mymethod = function(){console.log('method');}

Difference relates to perfomance. In first example method has to be created every time the constructor fucntion runs when method that declared with prototype is shared across all instances.

    1. What does this construction mean?
(function () {

})();

It is immediately-invoked function exrperssion(IIFE). The first pair of parentheses (function(){}) makes the function an expression and the second(in the end) calls the functions that results from evaluated expression. This pattern is often used to avoid pollution the global namespace, because all the variables used in the function are not vissible outside it’s scope.

  1. What is the result of the following code block.
    for (var i=0;i < 3; i++ )
    {
        setTimeout(function(){console.log(i);}, 1000)
    }
    

    Result is “3″ displayed 3 times. The loop finishes before the first timeout and displays the current value of i, which is 3. Since i is global variable we want to make it local and pass to the function like this:

    for(var i = 1; i < 3; i++) {
        (function(index) {
            setTimeout(function() { console.log(index); }, 100);
        })(i);
    }
    

    The result will be “12″. Here we have executed timeout immediately with IIFE and bound the current value to it.

Share this post:Tweet about this on TwitterShare on Facebook0Share on LinkedIn0Share on Google+0Share on Reddit0Email this to someoneDigg this