Thursday, September 25, 2014

JavaScript Function, Scope & Closure questions and answers

1. What is Scope in JavaScript?

Keyword:
global scope, local scope

Answer:
In JavaScript, scope refers to the region of your code in which it is defined.
Variables declared outside of a function definition are global variables and have global scope;
Variables declared within a function are local variables and have local scope. Function parameters also count as local variables and have local scope.

For example:
var scope = "global";         // Declare a global variable
function checkscope() {
    var scope = "local";      // Declare a local variable with the same name
    return scope;             // Return the local value, not the global one
}
checkscope()                  // => "local"

2. Explain JavaScript Scope Chain.

Answer:
In JavaScript, every chunk of code (global code or functions) has a scope chain associated with it. This scope chain is a list or chain of objects that defines the variables that are “in scope” for that code. When JavaScript needs to look up the value of a variable x, it starts by looking at the first object in the chain. If that object has a property named x, the value of that property is used. If the first object does not have a property named x, JavaScript continues the search with the next object in the chain. If the second object does not have a property named x, the search moves on to the next object, and so on. If x is not a property of any of the objects in the scope chain, then x is not in scope for that code, and a ReferenceError occurs.

In top-level JavaScript code, the scope chain consists of a single object: the global object. In a non-nested function, the scope chain consists of two objects: the object that defines the function, and the global object. In a nested function, the scope chain has three or more objects.

3. What is the difference between var x = 1 and x = 1?

Answer:
var x = 1 declares variable x in current scope. If the declaration is in a function, x is a local variable. If the declaration is outside of function, x is a global variable.

x = 1 tries to resolve x in the scope chain: if found, it performs assignment. If not found, it creates x property on a global object.

4. What are Function Scope and Hoisting?

Keyword:
variables declared within a function are visible before they are declared

Answer:
JavaScript doesn't support block scope, in which variables are not visible outside of the block (within curly braces). Instead, JavaScript uses function scope: variables are visible within the function in which they are defined and within any functions that are nested within that function.

With function scope, all variables declared within a function are visible throughout the body of the function, even visible before they are declared. This feature is called hoisting: JavaScript code behaves as if all variable declarations in a function are “hoisted” to the top of the function.

For example:
var scope = "global";
function f() {
    console.log(scope);  // Outputs "undefined", not "global"
    var scope = "local"; // Variable initialized here, but defined everywhere
    console.log(scope);  // Outputs "local"
}

5. How is the "this" determined in event handler?

Answer:
When the "this" is used in a event handler function, the "this" is set to the element the event fired from.
For example:
//<div class="intro">Intro</div>
var element = document.querySelector('.intro');
var showThis = function () {
  console.log(this);  //"this" refer to <div class="intro">Intro</div>
};
element.addEventListener('click', showThis, false);

When the code is called from an in–line handler, the "this" is set to the DOM element on which the listener is placed.
For example:
<button onclick="alert(this.tagName);">This</button>
The above alert shows "Button"

When the code is called from an inner function, the "this" isn't set and it refers to the global/window object.
For example:
<button onclick="alert((function(){return this}()));">This</button>
The above alert shows "[object window]"

6. What is the difference between call() method and apply() method?

Keyword:
call() requires a parameter list,
apply() requires an array of parameters.

Answer:
call() and apply() allow you to indirectly invoke a function as if it were a method of some other object. The first argument to both call() and apply() is the object on which the function is to be invoked; this argument becomes the this value within function body.

f.call(o);
f.apply(o);
These two lines equal to:
o.m = f; // Make f a temporary method of o.
o.m(); // Invoke it, passing no arguments.
delete o.m; // Remove the temporary method.

The main difference between them is that apply() lets you invoke the function with arguments as an array; call() requires the parameters be listed explicitly.
f.call(o, 1, 2);
f.apply(o, [1,2]);

f.call(o, a, b, c); // Fixed number of arguments
f.apply(o, arguments); // Forward current function's arguments to o directly

7. What is Closure in JavaScript?

Keyword:
the function defined in the closure remembers the environment in which it was created

Answer:
A closure is a function that refer to independent (free) variables. In other words, the function defined in the closure remembers the environment in which it was created.

A closure is created when an inner function is made accessible from outside of the function that created it. This typically occurs when an outer function returns an inner function.  When this happens, the inner function maintains a reference to the environment in which it was created, which means that it remembers all variables and their values that were in scope at the time.

For example:
function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

In the above example, add5 and add10 are two closures. They share the same function body definition, but store different environments. In add5's environment, x is 5, while for add10, x is 10.

8. How to emulate private methods with closures?

Answer:
Private methods are methods that can only be called by other methods inside the same class. JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures.

For example:
var myCounter = (function() {
  // private variable
  var _counter = 0;

  // private method
  function doCount(val) {
    _counter += val;
  }

  return {
    increment: function() {
      doCount(1);
    },
    decrement: function() {
      doCount(-1);
    },
    value: function() {
      return _counter;
    }
  };
})();

console.log(myCounter.value()); /* Prints 0 */
myCounter.increment();
myCounter.increment();
alert(myCounter.value()); /* Prints 2 */
myCounter.decrement();
alert(myCounter.value()); /* Prints 1 */

For the above code, the function returns an object with three methods: increment, decrement and value. They have access to the private method doCount and private variable _counter. But the outer world can not directly access them.

More JavaScript Function, Scope & Closure interview questions and answers: JavaScript Interview Notes

  • Explain the "this" keyword in JavaScript?
  • How is the "this" determined in prototype method?
  • How to find the min/max number in an array?
  • What does Function.prototype.bind() method do?
  • What is the arguments object?
  • What is the difference between setTimeout() and setInterval()?
  • What is Immediately-invoked function expression in JavaScript?
  • ......

JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.


SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play


No comments:

Post a Comment