Explore 100's Of Free Video Tutorials

Keep Learning, Keep Coding & Keep Sharing

JavaScript Local scope Vs Global scope

Notes:

Local scope Vs. Global scope

Scope indicates the accessibility and visibility of variables (i.e. life of a variable)
JavaScript variables are of local scope (function scope) or global scope

Local scope:
Any variable declared inside a function is considered as in local scope
can be accessible only inside that function where it is declared
Local variables will be available only in the function execution
Local variables are created as soon as the control enters the function body and deleted as soon as the control exits the function body.

Global scope:
Any variable not declared inside a function is considered as in global scope
can be accessible anywhere in the script
Global variables will be available throughout the script execution

Ex 1:
var a=10;
document.write("a= ", a, "<br/>"); // 10

function display()
{
document.write("a= ", a,"<br/>"); // 10
var b=20;
document.write("b= ", b,"<br/>"); // 20
}
display();

// error: b is not defined
document.write("b= ", b,"<br/>");

Ex 2:
var a=10;
document.write("a= ", a, "<br/>"); // 10

var b=30;
function display()
{
document.write("a= ", a,"<br/>"); // 10
var b=20;
document.write("b= ", b,"<br/>"); // 20
}
display();

document.write("b= ", b,"<br/>");//30

Interview Questions: