Interview Questions & Answers

javascript

  • The only one goal of closure is to create self contained functions, self contained code, self contained module.
  • When we create something self contained you have a self contained state and when you have self contained state that means you are avoiding global variables.

  • Closures are functions inside function and it make a normal function stateful.
  • <script>
        function SimpleFunction(){
          var x = 0;
          x++;
        }
        function ClosureFunction(){
          var x =0;
          function Increment(){
            x++;
          }
          return {
            Increment
          }
        }
        SimpleFunction();
        SimpleFunction();
        var ref = ClosureFunction();
        ref.Increment();
        ref.Increment();
    </script>

  • Its difficult to avoid global variables. But we can organize it properly by doing two things:-
  • 1. Put global variables in a proper Namespace.
  • 2. Module pattern using closures and IIF.

  • Global variables are needed in a project. So it is very difficult to avoid global variable but we have avoid global variables.
  • We can put global variable in a proper common namespace.
  • <script>
        var global = {};
        global.connectionString = “Test”;
        global.logDir = “d:\Logs”;
        var myGlobal = (function(){
          var connectionString = “Test”;
          function GetConnection(){
            return GetConnectionString;
          }
          return{
            GetConnection
          }
        })();
        var str = myGlobal.GetConnection();
    </script

  • “Use Strict” is a directive which says strictly checks if the variables are defined using the “var” keyword.
  • If not defined using var keyword or the let keyword
  • <script>
      “use strict”;
      var x = 10;
      function fun1(){
        y=100;
        console.log(x);
      }
      fun1();
      console.log(y);
    </script>

  • Without declaring VAR variable becomes Global.
  • <script>
      var x = 10;
      function fun1(){
        y = 100;
        console.log(x);
      }
      fun1();
      console.log(y);
    </script>

  • It can make application buggy and very hard to debug .
  • <script>
      var x = 10;
      function fun1(){
        console.log(x);
      }
      fun1();
    </script>

  • Global variables are accessible through out the webpage of the document.
  • <script>
      var x = 10;
      function fun1(){
        console.log(x);
      }
      fun1();
    </script>