MDN says:
Remember, the
await
keyword is only valid insideasync
functions. If you use it outside of anasync
function's body, you will get aSyntaxError
.
But that's not true.
Try this code in DevTools console, no errors, just result:
async function a(val) { return val; }
await a(10) // await is not inside async function
10
What's wrong with the code or docs?
Nothing is wrong.
You've found a special feature of the DevTools console! It is there to make it as easy as possible to experiment with async
-await
code in a live environment. You can imagine that any code you enter in the console is wrapped in an async
function automatically. In fact, as another answer pointed out, this is exactly what happens.
It's important to note that even though this works in the console, it is not a feature of JavaScript.
So, all of your observations are correct and expected! The MDN docs are accurate, because if you try to load a script on a page that uses await
outside of an async
function, it will error. On the other hand the DevTools console is designed to make this work (exclusively for developer ergonomics), so your code runs without any errors in the console.
This isn't the only trick the DevTools console has up its sleeve. In general if you really want to test how some code runs on a page, it's best to actually run the script on the page, not in the console.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With