JavaScript Closure


Most of developers use JavaScript Closure, JavaScript Closure means that an inner function always has access to the vars and parameters of its outer function. 

Creating a Nested function in JavaScript called Closure. 

Consider the Following JavaScript Closure example.

<script>
 function now_cal() {
 var name= "JavaScript Closure";
 function add(){ // add() is the inner function, a closure
           alert(name); // use a parent function's variable to alert
 }
   return add;
 }
var cal_func= now_cal();
cal_func();
</script>

Run the code and notice that Alert() statement show in popup and display the name, within the add function, which is the name declared in parent function, In this return the result of add() function and return to the now_cal() function,

Function can call using the variable and variable become the function to call like cal_func(), It's closure.


Now the Following Complete Example of JavaScript Closure


<html>
<body>
<h1> Javascript Closure </h1>

<script>
 function now_calculator() {
  var n = 0; 
  return {
    add: function(a,b) {
      n = a + b;
      return n;
    },
    multiply: function(a,b) {
      n = a * b;
      return n;
    }, 
    subtract: function(a,b) {
      n = a - b;
      return n;
    },


  };
}

calculate = now_calculator();

var add_res = calculate.add(3,1); // pass parameters and return the result
console.log(add_res);
alert("Addition => " + add_res);

var multiply_res = calculate.multiply(11,11); // Pass parameters and Return the result
console.log(multiply_res);
alert("Multiplication => " + multiply_res);

var subtract_res = calculate.subtract(10,5); // Pass parameters and Return the result
console.log(subtract_res);
alert("Substraction =>" + subtract_res);

</script>
</body>
</html>


No comments:

Post a Comment

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...