3

In the MDN docs on block-scoped variable declarations, let is said to not hoist. However, in babel, it seems to do just that in this example link to babel repl...

const obj = {
  prop: 1,
  test() {
    this::log();
  }
}

let log = function() { console.log(this) };
obj.test(); // logs "{ prop: 1 }" with no reference error. 

Am I misunderstanding something about hoisting / the temporal deadzone?

EDIT:

Looks like this actually is not an error, as by the time obj.test() is called, log has been initialized, and is no longer in the temporal deadzone, therefore the reference will resolve and there will be no error. This code runs fine in chrome (46.0.2490.80) for example...

(function() { 
  'use strict'; 
  let obj = { 
    prop: 1, 
    test: function() { 
      log.call(this);
    } 
  }; 

  let log = function() { 
    console.log(this); 
  }; 
  obj.test(); 
})()
Ben Southgate
  • 3,388
  • 3
  • 22
  • 31
  • Sounds like a bug in babel. You should open a ticket on their repo. This behavior does seem inconsistent with the browser's native behavior. – Madara's Ghost Nov 07 '15 at 16:53
  • In _ES5_ we don't have `let`, so the `let log` becomes `var log`, the `var` gets hoisted and is therefore referenceable early in the compiled code – Paul S. Nov 07 '15 at 16:54
  • @PaulS. That can be dealt around with the use of adding scopes and the such. The question is whether it's worth it or not (which is really up to the maintainers of babel to decide) – Madara's Ghost Nov 07 '15 at 16:55
  • @MadaraUchiha good idea, I just opened a ticket! – Ben Southgate Nov 07 '15 at 16:57
  • You can try `let` in an environment with native `let` support, Chrome for example, without Babel. `let` won't get hoisted there. – Andreas Blaesus Nov 07 '15 at 16:57
  • I'm sure this would be a _won't fix_ because of the added overhead of scopeing so much but maybe you could convince them to add a _warning in console_ – Paul S. Nov 07 '15 at 16:58
  • `let` *does* get hoisted. Given that you are not calling the `test` method before you initialise `log`, you don't run into the *temporal* dead zone. – Bergi Nov 07 '15 at 16:59
  • @MadaraUchiha: No, it's not a bug, it's expected behaviour. – Bergi Nov 07 '15 at 17:00
  • @Bergi How is it expected? When run by a browser supporting let, it triggers an error. – Madara's Ghost Nov 07 '15 at 17:01
  • @MadaraUchiha: Which browser are you testing this in? Works flawlessly in Chrome (with `::` replaced by `call` of course). You can even turn on "high compliancy" in the Babel REPL which enables TDZ and it still runs. – Bergi Nov 07 '15 at 17:04
  • @Bergi You are correct. My bad. – Madara's Ghost Nov 07 '15 at 17:06

0 Answers0