Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does if block create a new local scope inside a function scope?

Tags:

javascript

For example:

function example() {
   console.log("outside the if block above function b declaration"+b()); 
  function a() {
   return "you invoked function a";
  } 
  if (true) {
    console.log("inside the if block"+a());
    console.log("inside the if block above function b declaration"+b());
    function b() {
      return "you invoked function b";
    } 
  }
}

When i invoke this example() function, I get an error that b is undefined, but when I remove the 2nd line that invokes with function b defined inside the if block It's all ok?

like image 886
gpbaculio Avatar asked Apr 29 '17 10:04

gpbaculio


2 Answers

Yes and no. The keyword let does support a local scope in blocks. The keywords function and var work on the function level scope. They define an indentifier, when the block is compiled before execution. So you normally can call functions above the declaration.

In your example the function is declared conditionally. It will get declared after the condition is evaluated and before the inner block is executed. But when it gets declared, it is valid in the entire function's scope. Try moving the invokation below the if-block, and it will be known and executed.

like image 106
Quasimodo's clone Avatar answered Oct 26 '22 03:10

Quasimodo's clone


No, it does not. If blocks remain scoped to their containers. Your function B is undefined because the code which defines it never gets executed when blocked by the if statement. However, once the if statement is removed, the code defining the function is executed, defining the function.

Here is a jsfiddle demonstrating the concept.

function defining() {
    ifstmt = true;
    if(ifstmt) {
        var ifscope;
        ifscope = "yes";
    }
    console.log(ifscope); // logs "yes"
}

function notDefining () {
    ifstmt = false;
    if(ifstmt) {
        var ifscope;
        ifscope = "no";
    }
    console.log(ifscope); // logs undefined
}

defining()
notDefining()

in defining() the variable ifscope gets defined but clearly isn't limited to the scope of the if statement. In notDefining() the code defining ifscope gets skipped and therefore the console.log returns undefined.

like image 37
Michael.Lumley Avatar answered Oct 26 '22 03:10

Michael.Lumley