1

I work on an IDE for Javascript that lets developers evaluate their code. In a modern Chrome console, I can run:

eval(`try{function foo3(){console.log("Hi")}} catch(err){console.log(err)}`)

and foo3 will be defined and called fine. I can also run:

eval(`async function foo4(){console.log("Hi")}`)

and foo4 will be defined and called fine. But when I run:

eval(`try{async function foo5(){console.log("Hi")}} catch(err) {console.log(err)}`)

I get no error, but foo5 is not defined. Note that the difference between example 1 and example 3 is just "async" before "function". I would like foo5 to be defined. Clues greatly appreciated.

user1343035
  • 245
  • 3
  • 13
  • 1
    function declarations within blocks `{}` behave strangely due to web compatibility reasons and are often best avoided. [This](https://stackoverflow.com/questions/31419897/what-are-the-precise-semantics-of-block-level-functions-in-es6) seems like it is also related – Nick Parsons Nov 06 '21 at 04:39
  • 1
    What is the point of the `try`/`catch`? You'll never get an exception only from defining a function. – Bergi Nov 06 '21 at 05:22
  • Thanks Nick, it helps to realize this gray area of jS. – user1343035 Nov 06 '21 at 15:24
  • Bergi, the programmer might have typed in bad syntax for the function, so the outer try/catch can help catch that. – user1343035 Nov 06 '21 at 15:25
  • @user1343035 No, it doesn't. If the syntax is invalid, the entire statement doesn't get run. You'd need to place the `try` block around the `eval()` call to catch syntax errors. – Bergi Nov 06 '21 at 20:57
  • @user1343035 And btw, it's not a gray area. If you `"use strict"` mode, you'll get the consistent modern behaviour. – Bergi Nov 06 '21 at 20:59

1 Answers1

0

Well, you could invert your code slightly, to include the try/catch block, within your async function to get it going.

eval(`async function foo5() {try {console.log("Hi")} catch (err) { console.log(err)}}`);

foo5();
Salvino D'sa
  • 4,018
  • 1
  • 7
  • 19
  • 1
    By the info the OP provided, I assume the "evaluator" in the IDE they are coding is something like this: `eval(\`try{ ${CUSTOM_CODE_HERE} } catch(err){console.log(err)}\`)`, So moving the target function outside of the `try` probably won't work (that's just how I understood it tho). – NullDev Nov 06 '21 at 04:26
  • 1
    Well, [`eval`](https://www.w3schools.com/jsref/jsref_eval.asp) just executes the string as if it were an actual piece of `javascript` code. So inverting the code, should work fine I feel. – Salvino D'sa Nov 06 '21 at 04:33
  • NullDev, yes you have made a better description of my actual use case, thanks. Salvino I suspect you're right. Your answer was a quite clever "refactoring" of the problem. While not ideal, with a bit of work, it may well solve my problem. – user1343035 Nov 06 '21 at 15:31
  • Yep, please accept & upvote if you find this answer useful. – Salvino D'sa Nov 07 '21 at 04:25