Variable scope
When you write a variable in JavaScript, it can have a scope, which means it can be accessed in different parts of your code. The scope of a variable determines where that variable is accessible or visible within your code.
There are two types of scope in JavaScript: global scope
and local scope
.
Global scope
Global scope means that the variable is defined outside of any function, and can be accessed anywhere in your code, including within functions. Local scope means that the variable is defined within a function, and can only be accessed within that function.
Here's an example of global scope:
As you can see, the variable myName
is defined outside of the function sayMyName()
, but it can still be accessed inside the function.
Local scope
Now let's take a look at an example of local scope:
In this example, the variable myName
is defined inside the function sayMyName()
, so it can only be accessed within that function. If you try to access it outside of the function, you'll get a ReferenceError
.
When can we access a variable?
Basically, a variable can be accessed when it's in the same scope as the code that's trying to access it. If the variable is in a different scope, it can't be accessed.
Each function creates a new scope, so variables defined inside a function can't be accessed outside of that function. But inside that function, you can access variables defined outside of it.
You can think the scope like houses. Who are inside the house can see the ones outside, but the ones outside can't see the ones inside.
Be aware!
A good practice is to always declare your variables at the local scope, and not at the global scope. This is because if you declare a variable at the global scope, it can be accessed by any other code in your program, which can cause unexpected behavior.
If a function needs to access a variable, it's better to pass that variable as a parameter to the function, instead of declaring it at the global scope.
Can a variable defined inside a block be accessed outside of that block?