Basic JavaScript scopes and execution context

// Hello can some pls explain why i get ’ a is not defined’ thank you

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

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

var myVar = 1;
console.log(myVar);
c();
console.log(myVar);

What’s defined inside a function stays inside a function. a is only accessible inside b (ie it is scoped to b). You can’t call a from outside of where it is defined.

1 Like

So there is noway to get that value out of that scope?Just making it sure and thank you for answer! :slight_smile:

Functions have to return something, and then you need to keep hold of that return value somehow. The example is contrived to show you how you can’t access a, and how myVar is another thing that stays inside the function scope where it was defined.

When a function is not executed (like b in the example), it’s just code in a text file. It doesn’t do anything.

When a function is executed, it evaluates to a value, so the other stuff in there that isn’t returned out of the function is gone

So like:

function add(x, y) {
  function I_do_nothing_at_all() {
    return "Hi I'm just sitting here taking up space"
  }
  return x + y;
}

You can’t go and look at what x and y and I_do_nothing_at_all are, like

function notGonnaWork() {
  console.log(x)
  console.log(y)
  console.log(I_do_nothing_at_all)
  I_do_nothing_at_all()
}

because x and y and I_do_nothing_at_all aren’t anything real, they’re just some characters in a file. Even if you run that code and execute the function by doing add(1, 2), x and y are only assigned the values 1 and 2 while that function runs, for a split second, you still can’t log x and y. And that inner function is never executed, it’s just dead code. It’s the same with that function a inside b.

If you return that function out of a, then this happens:

function b() { 
  console.log("I'm B");
     
  return function a() {
    console.log("I'm A")
    } 
}

// call b
b() // logs "I'm B"
// b returns a function, so if I keep hold of it:
var myA = b();
// myA has been assigned the return value of `b`, which is a function.
// so I can now execute that:
myA() // logs "I'm A"
1 Like

I think i got it it makes sense thank you for help.