Scope of variables

ANSIF
2 min readMar 6, 2024

--

Global Scope — Variables and functions defined outside of any function are in the global scope. They can be accessed from anywhere within the program, including inside functions. Global variables are accessible from all scopes, but they should be used judiciously to avoid unintended side effects.

Local Scope — Variables defined inside a function are in the local scope of that function. They can only be accessed from within the function where they are defined. Once the function execution completes, the local variables are destroyed, and their scope ends.

var x = 2;
console.log(x);

function A()
{
var x = 5;
console.log(x);

B();
}

function B()
{
console.log(x);
}

A();

Output: 2 5 2

When function B is called from within function A, it first checks for the variable x within its own scope. Not finding x there, it then looks in the scope where it was originally defined, which is the global scope. In the global scope, there is a variable x with a value of 2. Therefore, function B prints out the value of x from the global scope, which is 2. It’s essential to understand that function B disregards the variable x from function A’s scope because it’s defined in the global scope, where function B itself is also defined. Thus, the output will be x = 2.

--

--

ANSIF
ANSIF

No responses yet