Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`function` declarations are function scoped, but `async function` declarations are block scoped?

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?

like image 986
joe Avatar asked Feb 24 '20 12:02

joe


People also ask

What is the difference between scoped and block scoped?

Function scoped variables: A function scoped variable means that the variable defined within a function will not accessible from outside the function. Block scoped variables: A block scoped variable means that the variable defined within a block will not be accessible from outside the block.

Why VAR is not block scoped?

Variables declared with the var keyword can NOT have block scope. Variables declared inside a { } block can be accessed from outside the block.

What is block scoping in Javascript?

Block Level Scope: This scope restricts the variable that is declared inside a specific block, from access by the outside of the block. The let & const keyword facilitates the variables to be block scoped.

What is a block scoped language?

Block scoping means declaring a variable, not just inside a function, but around any curly brackets like if statements or loops. The variable itself let i is still in memory, but the engine just won't allow you to access it like before when we used var.


1 Answers

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.

like image 137
Bergi Avatar answered Oct 20 '22 04:10

Bergi