7

Should the following code work?

if(true) {
  async function bar() {
    console.log("hello");
  }
}
bar();

Chrome 80 and Firefox 72 both throw a ReferenceError saying bar is not defined. So it seems like async function bar() {...} declarations are block scoped whereas function bar() {...} declarations are function scoped? Confusing if that's the case, but can someone just confirm that for me with a link to the relevant part of the spec?

Also, is there a way to make an async function declaration function-scoped when declared from within a block?

joe
  • 3,752
  • 1
  • 32
  • 41

1 Answers1

5

It seems like async function bar() {...} declarations are block scoped

Yes, just like normal. Function declarations are block-scoped in general.

… whereas function bar() {...} declarations are function scoped?

Not really, except in sloppy mode for legacy reasons. This does not affect async function and function* declarations, which don't need any backwards-compatibility.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • You used the terms "like normal" and "in general" there to refer to strict-mode code, specifically, right? I.e. code in a ES6 module script or where `"use strict";` has explicitly been written at the top of the script or function? – joe Feb 24 '20 at 15:09
  • 1
    @joe Yes, like in an ES6 module :-) Also I think there are some EcmaScript engines that don't implement Annex B at all. – Bergi Feb 24 '20 at 15:21