Javascript-Scope:
There are two types of scope in JavaScript:
- Global scope
- Local scope
Global Scope:
Javascript Variables declared outside of any function become global variables and Global variables can be accessed and modified from any function.
Example: Global Variable
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Scope</h2>
<p>A GLOBAL variable can be accessed from any script or function.</p>
<p id="global"></p>
<script>
var tutorialName = "i2tutorials";
myFunction();
function myFunction() {
document.getElementById("global").innerHTML = "I can display " + tutorialName;
}
</script>
</body>
</html>
OUTPUT:
JavaScript Scope
A GLOBAL variable can be accessed from any script or function.
I can display i2tutorials
Local Scope:
Javascript Variables declared inside any function with var keyword are called local variables. Local variables can’t be accessed or modified outside the function declaration.
Example: Local Scope
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Scope</h2>
<p>Outside myFunction() tutorialName is undefined.</p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
myFunction();
function myFunction() {
var tutorialName = "i2tutorials";
document.getElementById("demo1").innerHTML = typeof tutorialName + " " + tutorialName;
}
document.getElementById("demo2").innerHTML = typeof tutorialName;
</script>
</body>
</html>
OUTPUT:
JavaScript Scope
Outside myFunction() tutorialName is undefined.
string i2tutorials
undefined
