Why reference to constant before declaration does not throw?

49 views Asked by At

Why the following code does not throw at line (*)?

{
  function update() {
    console.log(this);
  }

  const THROTTLE_TIMEOUT = 1000;
  let throttled = false;

  function stopThrottling() {
    throttled = false;
  }

  function mouseMoveHandler(e) {
    if (throttled) return; throttled = true;
    setTimeout(stopThrottling, THROTTLE_TIMEOUT);

    update.call(Tracker); // (*)
  }

  //console.log(Tracker); // Throws

  const Tracker = {
    attached() {
      window.addEventListener('mousemove', mouseMoveHandler);
    }
  }

  Tracker.attached();
}
1

There are 1 answers

0
Thomas Sablik On

The function is called after the variable is set.

The variable Tracker is set between

//console.log(Tracker); // Throws

and

Tracker.attached();

The line

update.call(Tracker);

isn't called before

Tracker.attached();

Follow the program flow in your debugger or add some console.log debugging to see it.