Confused why closures don't work in this JS code snippet

54 views Asked by At

I am reading this textbook Crafting Interpreters and on Chapter 11(Resolving and Binding) this code snippet in Lox (the language we are trying to Interpret) is supposed to print "global" twice, since we want to implement closures:

var a = "global";
{
  fun showA() {
    print a;
  }

  showA();
  var a = "block";
  showA();
}

An equivalent version in JavaScript would be this:

var a = "global";
{
  function showA() {
    console.log(a);
  };

  showA(); // Prints "global"

  var a = "block";
  showA(); // should still print "global"
}

Running the javascript code prints global and then block. However I was expecting it to print 2 globals because of closure. I don't understand what I'm doing wrong here. Thank you.

0

There are 0 answers