Close

December 18, 2015

JS-Variable Scope

Types of JavaScript variables:

There can be two types of variables in JS,

● local variable

● global variable

Scope of a variable:

A variable’s scope is simply the context in which the said variable exists and is accessible.

Local variables have function level scope, whereas global variable, ie., the variables declared

outside function definition, are available throughout the application.

Example of local and global variable scope:

var name = “I am a global variable”; // This is same as writing the statement without var keyword

​function displayName () {

var name = “I’m a locally stored variable”; // local variable, accessible inside

displayName function​

console.log (name); // “I’m a locally stored variable”

}

console.log (name); // “I am a global variable”

Declaring global variable inside a function:

Now that we know that the variable declared using var keyword inside a function has local

scope, how do we declare a global variable from within a function?

The answer to this question is, by dropping the keyword var.

ie., if you want to declare the variable in global scope from inside a function, you just declare

and initialize it without using the var keyword.

function declareGlobalInsideFn(){

var localName = “This is a local variable”;

globalName = “this is a global variable”;

console.log(localName); // “This is a local variable”

}

console.log(globalName); // “This is a global variable”

Note: If you declare 2 variables, one local and another global but both with the same name,

local variable will always have the priority over global variable when you try to access them.

Tip: You should avoid declaring variables in global scope unless it’s absolutely required to do

so.

Conclusion:

Always keep in mind the scope where you are declaring the variable.

Decide the type of the variable you declare based on how you want to use them, more

importantly in what scope you want them to be in.

Do not violate global space with variables which you will be using only inside a function, declare

them locally inside the function.

Leave a Reply

Your email address will not be published. Required fields are marked *