franza
franza

Reputation: 2327

In Javascript does the variable is captured by closure even if it is not used?

Maybe this is a stupid question but I couldn't find an answer on it. Assume we have code like this:

function makeFunc() {
  var name = 'Billy';
  var unusedVariable = 'unused';
  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = makeFunc();

As far as I understand, in this example a variable name will be collected when there won't be references on it, so it will live while the closure myFunc lives. But will unusedVariable live while myFunc lives? In other words, does displayName() 'captures' this unusedVariable even if it is unused?

Upvotes: 0

Views: 145

Answers (1)

vivek_nk
vivek_nk

Reputation: 1600

yes. All the variables created in "makeFunc" scope will exist in the closure, irrespective of whether used or not. To be precise, that is what closure means. Inside "displayName", you 'can' (not "must') refer to both those variables.

Upvotes: 1

Related Questions