Answers for "closure definition in javascript"

3

closure in javascript

// closure in javascript
-> A closure gives you access to an outer function’s scope
   from an inner function

const outerFun = (a) => {
  let b = 10;
  // inner func can use variable/parameter of outer funcion
  const innerFun = () => {
    let sum = a + b; 
    console.log(sum);
  }
  return innerFun;
}
let inner = outerFun(5);
inner();
Posted by: Guest on September-15-2021
4

closure in javascript

function makeFunc() {
  var name = 'Mozilla';
  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = makeFunc();
myFunc();
Posted by: Guest on July-04-2020
0

What is Closures in JavaScript

/*A closure is the combination of a function bundled together (enclosed) with references
to its surrounding state (the lexical environment). In other words, a closure gives you 
access to an outer function’s scope from an inner function. In JavaScript, closures are 
created every time a function is created, at function creation time.*/

function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() { // displayName() is the inner function, a closure
    alert(name); // use variable declared in the parent function
  }
  displayName();
}
init();
Posted by: Guest on September-25-2021
0

js closure

// global scope
var e = 10;
function sum(a){
  return function(b){
    return function(c){
      // outer functions scope
      return function(d){
        // local scope
        return a + b + c + d + e;
      }
    }
  }
}

console.log(sum(1)(2)(3)(4)); // log 20

// You can also write without anonymous functions:

// global scope
var e = 10;
function sum(a){
  return function sum2(b){
    return function sum3(c){
      // outer functions scope
      return function sum4(d){
        // local scope
        return a + b + c + d + e;
      }
    }
  }
}

var sum2 = sum(1);
var sum3 = sum2(2);
var sum4 = sum3(3);
var result = sum4(4);
console.log(result) //log 20
Posted by: Guest on July-12-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language