1

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](https://tc39.es/ecma262/#sec-block-level-function-declarations-web-legacy-compatibility-semantics). In general, the advise is to just not use block scoped functions. – VLAZ Aug 03 '22 at 06:21
  • 1
    Related on block-level functions (although some are in different contexts): [What are the precise semantics of block-level functions in ES6?](https://stackoverflow.com/q/31419897) | [Function declaration in block moving temporary value outside of block?](https://stackoverflow.com/q/58619924) | [How does this hoisting work with block scope?](https://stackoverflow.com/q/66756997) | [a variable and function with same name returns an error inside a block](https://stackoverflow.com/q/57006745) – VLAZ Aug 03 '22 at 06:30
  • 1
    @VLAZ No, the general advise is to always use strict mode, where everything works like one would expect. – Bergi Aug 03 '22 at 08: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 block – Bergi Aug 03 '22 at 08:11

0 Answers0