IF the condition is true, let’s say 5 minutes later after JavaScript is loaded and set synchronously, will it create the function?
The function will be created as soon as the if
runs, immediately.
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?
This behavior will be the same regardless of if the function is declared in an if
block or not: if nothing can possibly reference the function in the future (for example, if the block ends and nothing inside the block has a reference to the function), it will eventually be garbage collected. The function may still "exist" in memory for a time until the GC runs.
For example, it should be clear that the following function should always continue to exist, at least until you reload the page:
// IIFE, to get off the top level
(() => {
if (true) {
function foo() {
console.log('clicked');
}
window.addEventListener('click', foo);
}
})();
This is because the addEventListener
has been passed a reference to the function.
But the following foo
function will get GC'd (maybe a second or few after the page is loaded - it depends on the underlying engine, and isn't visible to Javascript):
// IIFE, to get off the top level
(() => {
if (true) {
function foo() {
console.log('clicked');
}
}
})();
If nothing has saved a reference to the function by the time the block that scopes the variable has finished, the function will not be accessible anywhere, and will be GCd.
The rest of the question looks to be essentially the same as: "where can the function be referenced", which is best described in Bergi's answer here. It's a bit complicated, and the behavior differs depending on whether you're using strict mode, the ES version of the environment, and the environment itself (implementations do not always conform to the specification).
For predictable, easy-to-read code, probably best to simply never use function declarations in non-function blocks; only use function declarations when directly inside function blocks.
(Note that function expressions, where the function is used as a value and passed to something or immediately invoked or explicitly assigned to a variable, are not the same as function declarations - function expressions are fine, it's just the weird behavior of function declarations that's problematic. Also note, per comment, that a "function declaration" is sometimes called "function statement".)