I have a doubt regarding how the function declaration are invoked in JavaScript.
I have read somewhere that function declaration can be accessed anywhere within the function it was declared on.
Lets say I declare a function within a block of code so it will be accessible anywhere or maybe outside the block as well.
But when I try to invoke the function before the block of code, I get an TypeError. But this error is not happening when I invoke the function after the block of code. Please explain why the function is not getting invoked before the block of code.
function globalFunc() {
//..
// ..
funcName(); // not accessible - TypeError
{
function funcName() {
console.log("Hey");
}
}
funcName(); // accessible
}
globalFunc();
-
2"I have read somewhere that function declaration can be accessed anywhere within the function it was declared on." this used to be the case. As of ES6 functions are block scoped. That leads to some peculiarities in how they are handled which are covered by the web compat semantics. In general, the advise is to just not use block scoped functions.VLAZ– VLAZ2022年08月03日 06:21:33 +00:00Commented Aug 3, 2022 at 6:21
-
1Related on block-level functions (although some are in different contexts): What are the precise semantics of block-level functions in ES6? | Function declaration in block moving temporary value outside of block? | How does this hoisting work with block scope? | a variable and function with same name returns an error inside a blockVLAZ– VLAZ2022年08月03日 06:30:21 +00:00Commented Aug 3, 2022 at 6:30
-
1@VLAZ No, the general advise is to always use strict mode, where everything works like one would expect.Bergi– Bergi2022年08月03日 08:09:04 +00:00Commented Aug 3, 2022 at 8:09
-
"I declare a function within a block of code so it will be accessible anywhere or maybe outside the block as well." - no, it should be accessible only inside of the blockBergi– Bergi2022年08月03日 08:11:53 +00:00Commented Aug 3, 2022 at 8:11
Explore related questions
See similar questions with these tags.