-1

Why does the hello() function appear in two different scopes?

function outerScope(){


    for(let i=0;i<10;i++){
        function hello(){
            console.log("Hello from hello",i);
        }
        console.log(hello.toString());
        hello();
    }

}

outerScope();

As shown below (Block and Local):

enter image description here

Nagev
  • 7,120
  • 2
  • 46
  • 53
  • You don't need to when using `let`. – evolutionxbox May 23 '22 at 12:59
  • Does this answer your question? [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – evolutionxbox May 23 '22 at 12:59
  • It’s not super-clear what you’re asking. – Dave Newton May 23 '22 at 13:02
  • @daveNewton in scope we can see that two hello functions are declared. why it is happening – Herat Makwana May 23 '22 at 13:07
  • @HeratMakwana A single `hello` function is declared. – Dave Newton May 23 '22 at 13:10
  • 1
    @DaveNewton isn't this related to semantics of [function declarations inside block scopes](https://www.ecma-international.org/ecma-262/10.0/#sec-block-level-function-declarations-web-legacy-compatibility-semantics)? And isn't the `hello` function redefined for each iteration? – Yousaf May 23 '22 at 13:17
  • @Yousaf Yes, it is redeclared. The OP stated in a comment that “two `hello` functions are declared” which is incorrect whether or not redeclarations are counted. Whether or not the OP is asking about differing implementations of block-level function declarations pre-ES2015 is unclear (and IMO unlikely) which is why I commented it wasn’t clear what was being asked. – Dave Newton May 23 '22 at 13:40
  • 1
    @DaveNewton Fair enough. As far as I understand OP's question, they are asking about why is the `hello` function shown in the local score as well as the block scope (as shown in the image). And I think that's because of block-scoped `hello` function being assigned to a variable declared with var in the local scope of the `outerScope` function. For OP's reference: https://stackoverflow.com/questions/68736679/scope-of-variables-and-functions-inside-if-block-in-javascript – Yousaf May 23 '22 at 13:44
  • See https://stackoverflow.com/questions/31419897/what-are-the-precise-semantics-of-block-level-functions-in-es6. Use strict mode to get the expected single variable! – Bergi May 23 '22 at 13:50
  • @Yousaf Ah, I see what you're saying; makes sense. – Dave Newton May 23 '22 at 13:51
  • What do you mean by two different scopes ? What two scopes are you talking about – Ernesto May 28 '22 at 04:32
  • @Ernesto The block and the function scope, as seen in the screenshot of the debugger. There are two `hello` variables. The question is quite clear to me. – Bergi May 28 '22 at 20:18

0 Answers0