Javascript scope, global and local variables

Javascript global variable can be declared outside a function with the keyword var and it can be accessed or modified in a function on the same page. It can also be declared inside a function without the keyword var. Variables declared inside a function with the keyword var is a local variable. Local variable can only be accessed within the function it was declared and it is deleted when the function completed its execution.

Declare a global variable outside a function with the keyword var, print it out in a function.
[code language=”javascript”]
var globalA=3;
function printGlobalVar()
{
console.log("Global variable globalA is: "+globalA); //3
}
printGlobalVar();
[/code]

Change the value of a global variable in a function and it will be reflected outside the function.
[code language=”javascript”]
function changeGlobalVar()
{
globalA=5;
}
changeGlobalVar();
console.log("Global variable globalA is now changed to: "+globalA); //5
[/code]

Declare a global variable inside a function without using the keyword var, and it automatically becomes a global variable.
[code language=”javascript”]
function declareGlobalVar()
{
globalB=30;
}
declareGlobalVar();
console.log("Global variable globalB was declared in a function and it’s value is: "+ globalB);
[/code]

Declare a local variable in a function with the keyword var, it only lives inside the function and it is deleted after the function completes it’s execution.
[code language=”javascript”]
function declareLocalVar()
{
var localVar=50;
console.log("I am printing the local variable localVar in the function it is declared, the value is: "+ localVar);
}
declareLocalVar();
console.log("Trying to print the local variable localVar outside the function it was declared, but getting undefined: "+localVar);
[/code]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search