Local vs Global scope – JavaScript

Local scope

Let’s start by declaring a variable inside a function called cool (just a name) to understand the difference between local and global scope

Let’s declare a variable called localVariable with type var in our function as below

var cool = function (){
 var localVariable = 10;
 console.log('Inside function: ' +localVariable)
}
cool();
console.log('Outside variable: ' +localVariable);

And we call our function, and also we are trying to write our variable value inside and outside the function in the console.

Once the following line is executed

console.log('Inside function:' +localVariable)

We will be getting output as

Inside function: 10

Whereas when the following line is executed

console.log('Outside variable: ' +localVariable);
Uncaught ReferenceError: localVariable is not defined(…)

We’re getting above error because the localVariable is a local variable and its scope is available within the function only.

Global scope

Let’s edit the same function by renaming the localVariable into localVariable2

And this time we are going to remove the variable type in our code.

Let’s execute and check what will be output.

var cool = function (){
 var localVariable2 = 10;
 console.log('Inside function: ' +localVariable2) // Inside function: 10
}
cool();
console.log('Outside variable: ' +localVariable2); //Outside variable: 10

Now the output will be

Inside function: 10
Outside variable: 10

The interesting thing happening when we are initializing a variable without declaring the type, the JavaScript decides to make it as Global variable with Global scope.

When the variable which is initialized inside a function is assumed as Global scope by JavaScript, we can able to use it outside the function too.

JavaScript has function scope, not block scope. 

Let’s see another example about local and global scope.

var myVariable= "global"; // global
var cool= function() {
 var myVariable = "local";
 console.log(window.myVariable); // global
 console.log(myVariable); // local
}
cool();

Output

global
local

Here we are writing a global and local variable inside the function just by differentiating using window from browser environments.
We can access the variable as the property of global object (using window). And it’s not recommended to use window to access global objects.

Happy exploring JavaScript 🙂

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s