2
$\begingroup$

I am currently reading the Crafting Interpreter book and I have a question about the Resolving and Binding chapter

The author gave this example to illustrate the problem with the implementation at that point in the book.

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

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

The problem being that this prints

global
block

The argument the author is making is that, once the variable is captured as a closure, it should not be possible to change it, hence the second call to showA() should not give a different result from the first call.

The author makes the claim this is an issue to be fixed and the chapter is dedicated to fixing it.

But is this really an issue? If I run the JavaScript version of the code

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

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

I get exactly the output the author claims to be wrong. That is:

global
block

Is the author mistaken to claim this is a bug? Or the author is correct and JavaScript has this bug?

$\endgroup$

1 Answer 1

3
$\begingroup$

The scope of variables created with the var keyword in JS is pretty unintuitive, at least if you're already familiar with how other languages handle scope. You can get some more info on how closures and scope interact in JS on this page --> Closures - JavaScript | MDN

In this case, the problem is that a pair of curly brackets doesn't really create a new scope. Therefore, the second declaration of a gets converted to an assignment to the first one. In contrast, this code:

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

in which I have moved the definition of showA() out of the brackets and declared the second a with let , works "as intended" (i.e. it prints global twice).

Importantly, this behaviour isn't a bug, as it conforms to the specifications of JavaScript. But it runs counter to how most other languages work (apparently including how Mr. Nystrom intends his language to work in the book you're reading).

$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.