6

I am running Edge/15.15063. 'Can I Use' says const should work.

Running:

const x = 'woo'

Then:

console.log(x)

Returns

'x' is undefined

Screenshot:

enter image description here

Why isn't const working?

mikemaccana
  • 110,530
  • 99
  • 389
  • 494

2 Answers2

2

I suspect that the Edge console is using a with statement under its covers like other implementations did. This would explain vars and even function declarations being hoisted outside into the global scope, but let and const will be locked into the block scope:

with (…) {
    const x = 'woo'
}
// next input:
with (…) {
    console.log(x) // obviously undeclared
}

Try entering them in multiline mode, in a single evaluation - there they should work.

But you also might want to file a bug, as the console is indeed expected to feel like evaluating things in the global scope.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    The last comment on that answer you linked to pretty much says it all: "Few weeks ago we moved our console implementation in Chrome from with block to some symbol magic because with block blocked some ES6 features :)" – Jared Smith May 31 '17 at 17:35
  • @JaredSmith Ha, perfect! Didn't bother to read it, I just wanted to link anything that showed the implementation approach. – Bergi May 31 '17 at 17:37
1

I think I figured this out, but this is as much a guess as an answer. Too long for a comment though.

I think what's happening is that const and let do not create implicit globals when used in the top-level scope in the same way var does. Although top-level variables created with const and let are global, they are not properties of the global window object.

If the MS console is relying on that implicit window property creation for accessing variables created in the console, then const and let will not work.

I am unsure of the inner workings of Chrome Dev Tools, but it seems to create an anonymous function wrapper for code executed in the console:

throw new Error;

VM679:1 Uncaught Error at anonymous:1:7

(function() { throw new Error; })();

VM759:1 Uncaught Error at anonymous:1:21 at anonymous:1:33

I am unsure if there is other sandboxing going on here, I didn't necessarily find a lot of documentation on it.

Jared Smith
  • 19,721
  • 5
  • 45
  • 83