SiteMap  | About    

JavaScript global variable

Like other programming languages, JavaScript also has local and global variables . In JavaScript, objects and functions are also variables.

The scope specifies from where you can access a variable and whether you have access to the variable in that context. JavaScript variables has two scopes : global and local. A variable that is declared outside a function definition is called global variable, and its value is accessible and modifiable throughout your program. A variable that is declared inside a function definition is called local variable . It is created and destroyed every time the function is executed, and it cannot be accessed by any code outside the function.

JavaScript Local Variables

A variable that is declared within a JavaScript function has become local to the function and it can only be accessed within the function.


Local variables are created when a function starts, and deleted when the function is completed.

JavaScript Global Variables

A variable that is declared outside of a function definition is called a Global Variable and it has global scope, all scripts and functions on a web page can access it and modify throughout the program.


Here a Global Variable declared as total. Then add values to the total inside a local function addValue(). Next, dispValue() function display the value of total. Here you can see the global variable value modify inside a local function and the new value is displayed in another local function. It happens because of the scope of Global Variable.

Automatically Global

If a variable is assigned a value without first being declared with the var keyword, it is automatically added to the global context and it is thus a global variable:


Here you can see, the variable total is not declared. Inside the addValue() function variable total assigned a value. So, its scope is global because its not declared.

Note: Accessing a global variable is required a lot of times. If a variable is going to be used throughout the program it is important that you declare the variable in global scope . But, because JavaScript allows re-declaration of same variables, it can easily become a problem if a function is using a variable with same name as global variable in its scope. (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.