1

I have a question about a closure in JS. Below is the given fonction:

function multiplicationParDeux() {
 var chiffre = 10;
 var fonction = function() { console.log(chiffre * multiplicateur); }
 chiffre = chiffre * 2;
 var multiplicateur = 10;
 return fonction;
 }
 var maFonction = multiplicationParDeux();
 maFonction(); //Output: 200

How comes that the output is 200? I declared my multiplicateur variable after the closure , how does the console.log(chiffre * multiplicateur); part recognize the multiplicateur variable?

asked May 19, 2018 at 10:29
1
  • 2
    fonction only tries to read what's in multiplicateur when fonction is called, not before, so after multiplicationParDeux returns, multiplicateur has gotten 10 assigned to it. Commented May 19, 2018 at 10:31

2 Answers 2

1

Closuring does not mean that the variables are copied, but rather that the function keeps a reference to the outer scopes variables.

answered May 19, 2018 at 10:31
Sign up to request clarification or add additional context in comments.

Comments

0

Your inner function - fonction drags with itself a record of variables with their values from its lexical scope (referencing environment) when returned from its enclosing function - multiplicationParDeux or executed outside of its own lexical scope.

When you are returning fonction, you may imagine its closure as an object with the following properties, that serves as a binding for free variables inside of fonction.

chiffre: 20,
multiplicateur: 10

And each time the fonction is executed, it consults this closure if it contains bindings for its free variables (chiffre and multiplicateur), and since it does, the outcome is indeed 200.

Important note, you don't create the closure, JS engine does so it is not created at author-time (although you may deduce the contents of the closure just by inspecting the function's lexical scope) but when JS engine is executing your code and decides that the closure will be needed.

answered May 19, 2018 at 10:39

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.