Scope specifies the accessibility of a variable in a program.
Javascript variables have 3 scope
- Local
- Global
- Automatically Global
Local scope
A variable declared inside a function. These variables can be accessed (used) only inside the function where it is declared, not outside of it.
<script>
function demo() {
// Local variable
var x = 12;
}
</script>
Global scope
A variable declared outside of a function. These variables can be accessed anywhere in the script and in webpage.
<script>
// Global Variable
var x ="Hello";
function demo() {
alert(x);
}
</script>
All javascript global variables belongs to Window object.
Automatically Global
A variable becomes automatically global, when is assigned a value without being declared.
<script>
function demo() {
x = 12;
}
demo();
document.write(x);
</script>
Lifetime of variables – javascript
Lifetime of a variable in javascript depends on the scope of a variable.
- Local variable lifetime starts inside a function & ends when the function execution is completed.
- Global variable lifetime ends when the webpage is closed.