samedi 29 février 2020

Reasons to or not to declare functions in an if-statement

I need some confirmations on what’s happening behind the screen.

There’s an article in MDN that said that we shouldn’t declare functions in a block-level, such as, inside an if-statement. Because it’s inconsistent throughout browsers and anything to do with pre-ES2015 (or pre-ES6).

The function inside the if-statement will not be created unless the condition is true.

I was wondering, IF the condition is true, let’s say 5 minutes later after JavaScript is loaded and set synchronously, will it create the function? Does it still have memory of the code in order to create the function, or is it dumped in unused code and all?

I would like to know whether the function still exists even after the if-statement is completed. Is it accessible? How long is it accessible? Is it accessible until the if-condition is false? Does the result differ from ES6 and pre-ES6? I’ve heard there’s no scope pre-ES6 in if-statements.

e.g.

if (condition) { function foo() {console.log(“hello world”); } }

I was confused after reading an article in MDN on ‘Functions’ under ‘block-level functions in non-strict code’: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions

Aucun commentaire:

Enregistrer un commentaire