0

Ok so just a quick one... I REAAAAAALLLLY am not understanding scope at all. Do some reason whenever I put a variable inside of a function it's undefined. It seems the only way it works it to declare it OUTSIDE of a function. So what gives? Am I simply misunderstanding the concept of local and global variables? Because it seems global variables are the only ones that work...

Edit:

Simple example...

let a = 'something';
function myFunction() {
    // Code block
};

This works

But the following gives me undefined variables:

function myFunction() {

    let a = 'something';

    // Code block
};

2 Answers2

4

First lets take a look at the differences between local and global variables.

LOCAL VARIABLES - Any variable defined inside of a function or loop. If the variable is defined in a certain function/loop, it can only be accessed in that function/loop.

For example:

function number() {
  let a = 0;
  
  // Can access a here.
}

// Cannot access a here.

GLOBAL VARIABLES - Any variable that is not defined inside of any function or loop. These variables can be accessed anywhere.

For example:

let b = 0;
function number() {
  // b can be accessed here.
}
// b can be accessed here.

The scope of a variable is where it can be accessed in. For ex, a scope of a local variable that is defined inside of function number() is the number() function since it can only be accessed there.

One more quick thing (Credit to Mikael Lennholm) var doesn't scope a variable to a loop (or any non-function statement block), it only scopes it to the current function. To scope a variable to any statement block you have to use let/const

Now let's look at your examples:

Here is the first example:

let a = 'something';
myFunction();
function myFunction() {
    console.log(a);
};

That works fine, and that's what you said.

Here is the second example you said doesn't work:

function myFunction() {

    let a = 'something';

    console.log(a);
};

myFunction();

But, if you click the run button, you'll actually see it does work, it does get logged. If you after this go and check in the console what the variable a is of course it will be undefined, since a can be only accessed in the myFunction() function, and the console is not in that function.

You said that the script doesn't work, it's most probably because of something else (if it was because of this there would be an error in the console). You can try posting the website here and I can help you.

Hope this helped you :)

Sheshank S.
  • 3,053
  • 3
  • 19
  • 39
1

Global variables are variables that you have access to them anywhere in your codes.

Local variables are limited to their scopes like a function, module, class and etc.

if you define a local variable it can be accessible in the nested level like closures.

if you define a global variable and you define the same name as local variable , the local overwrite the global, then be careful.