Total Pageviews

Friday 30 August 2019

JavaScript Interview Question | Closure

In many interview question nowdays there is a popular interview question based on JavaScript closure and that is:


Input:    messageWord(‘2’)(‘3’)(‘4’)

Output: ‘234’

Solution:

function messageWord (x){
  return function(y){
      return function(z){
        return x + y + z;
      };
  };
}

JavaScript Closure


JavaScript Closure: A closure is the combination of a function (inner function) which have access to the parent scope (outside function variable).            

Advantages of closure:

1)      In the object-oriented programming paradigm, encapsulation is one of the key features. Encapsulation hides the inner work of an object from the outside world. But as JavaScript is a scripting language it doesn’t have encapsulation feature.

Here Closure comes in a picture, with the help of “Closure” we can access the parent function variable and arguments.
2)      Example:

var myFun = (function () {
    var privateFun = function () {
        alert(' privateFun ');
    }

    return {
        publicFun : function () {
            privateFun();
        }
    }
})();

In this example, I can access the publicFun but not privateFun.
3)      Closures are helpful in APIs callback functions requirement.

There are many examples available for closure, if you want to explore more.


Microsoft Logo using flexbox and Reactjs

 <!DOCTYPE html> <html> <head>     <script src="https://unpkg.com/react@18/umd/react.development.js" crossori...