Pergunta de entrevista da empresa Infosys

Clossure example

Respostas da entrevista

Sigiloso

18 de jan. de 2020

Closure is function inside function. Example: var add = (function () { var counter = 0; return function () {counter += 1; return counter} })();

Sigiloso

30 de jul. de 2022

A: 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. Example: -------- function init() { var name = 'Mozilla'; // name is a local variable created by init function displayName() { // displayName() is the inner function, a closure console.log(name); // use variable declared in the parent function } displayName(); } init(); Description: ------------ init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() and is available only within the body of the init() function. Note that the displayName() function has no local variables of its own. However, since inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().