-2

For a function, does it get the variable scope during the declaration, or before the run time?

I tried the first part of code below and it doesn't work. The second part works. Can somebody shed some insight on the difference?

//// does not work
function a() {
    console.log(v1);
}

function b() {
    let v1 = 1;
    a();
}

b();

//// does work

function a() {
    console.log(v1);
}

function b() {
    a();
}

let v1 = 1;
b();
python_dev6
  • 27
  • 1
  • 3
  • lexical scope is set at declaration, what we call closure. if you declare a inside of b in the first case, it would work fine. – dandavis Oct 09 '19 at 21:33
  • this is an example of dynamic vs static (lexical) scoping. See https://stackoverflow.com/a/22395580/989121 for the explanation. – georg Oct 09 '19 at 21:34
  • Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Herohtar Oct 09 '19 at 21:36

2 Answers2

0

OK, Let's Look at this:

//// does not work
function a() {
    console.log(v1);
}

function b() {
    let v1 = 1;
    a();
}

b();

In the above snippet of code, you have 2 functions (a() and b()) and invoke the method b() from your "main" function (which is unnamed but there). In a(), you try to directly access a local-scope variable from b() - which you can't.

//// does work

function a() {
    console.log(v1);
}

function b() {
    a();
}

let v1 = 1;
b();

So in this snippet of code, you also have a() and b() - as well as a variable v1. Since this is declared in the public space (before invoking b() - which then invokes a()), it is also available within the methods that you invoke.

J. Murray
  • 1,460
  • 11
  • 19
-1

The let keyword gives a variable block-level scope, meaning the v1 variable in b() is only usable inside b(). a() does not know what v1 is.

//// does not work
function a() {
    console.log(v1);
}

function b() {
    let v1 = 1;
    a();
}

b();

In this example, v1 is being set in the global scope, so all your functions will recognize it.

//// does work

function a() {
    console.log(v1);
}

function b() {
    a();
}

let v1 = 1;
b();
symlink
  • 11,984
  • 7
  • 29
  • 50