Lexically, what happens when we return a variable within a method that is declared in the function of that method?

Asked

Viewed 41 times

4

Someone helps me understand the context of the execution of this code?

  1. myVar is declared in Global;
  2. myVar is declared in a();
  3. b() is executed and myVar is declared in b();
  4. myVar is not found in c():

doubt: shouldn’t he go down to look at b() or global? and bring some of the two?

function b () {
        function c() {
            console.log(myVar);
        }
        c();
        var myVar = 3
    }
function a() {
     b();
     var myVar = 2;
}

let myVar = 1

a();

1 answer

3


Each function creates its scope. The var when declared/used within a function declares that variable and blocks access to variables with the same name outside that scope. However, in the lines preceding the line where var is used, the variable value is not yet defined...

Javascript can use declared functions before running the code but variables are only used when the code reaches the line where they are. This is called Hoisting and the difference is:

function add() {} // function declaration - disponível em todo o escopo

var add = function () {} // function expression - declarada em todo o escopo,
                         // mas só disponível depois da linha ter sido corrida

Look at the example:

function a() {
  b();
  console.log(1, foo, typeof foo); // 1 undefined undefined
  var foo = 'bar';
  console.log(2, foo, typeof foo); // 2 bar string
  try {
    console.log(3, inexistente, typeof inexistente); // dá erro

  } catch (err) {
    console.log(4, err.message); // 4 inexistente is not defined
  }

  function b() {
    console.log(5, foo); // 5 undefined - a função corre mas a variável não
  }
}

a();

In the case of the variable with the name inexistente the code knows that even if it has not been declared on the lines being executed, that variable is never declared. Hence the error.

Note: execution context refers to the this, your question refers to Hoisting and scope of variables.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.