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.

var globalA=3;
function printGlobalVar()
{
	console.log("Global variable globalA is: "+globalA); //3
}
printGlobalVar();

Change the value of a global variable in a function and it will be reflected outside the function.

function changeGlobalVar()
{
	globalA=5;
}
changeGlobalVar();
console.log("Global variable globalA is now changed to: "+globalA); //5

Declare a global variable inside a function without using the keyword var, and it automatically becomes a global variable.

function declareGlobalVar()
{
	globalB=30;
}
declareGlobalVar();
console.log("Global variable globalB was declared in a function and it's value is: "+ globalB);

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.

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);

Search within Codexpedia

Custom Search

Search the entire web

Custom Search