JS: Async function expression

By Xah Lee. Date: .

Async function expression, arrow function syntax

Async function can also be written as expression.

async () => { body }

console.log(async (x) => {});
// [AsyncFunction (anonymous)]

Async function expression, function keyword syntax

in expression context, async function with the keyword function is also an expression.

typically when you assign it to a variable.

// this is an async function expression, anonymous
const ff = async function () {};

// this is an async function expression, named xx.
const gg = async function xx() {};
// both xx and gg can be use in the body of the function for recursion.
// xx is preferred because it is a explict name of the function.

note, keyword const and let do not have name hoisting. meaning, code using them must come after the assignment.

Immediately Invoked Function Expression

if you have the code async function {body} at top level of source code, but you want it to be an function expression and wantto call it inline, you must add parenthesis.

(async function () {})();