Just like object-oriented programming programming languages (like C++, C# and Java), a JavaScript variable also has two scopes: global and local. Like object-oriented programming programming languages, JavaScript before ECMAScript 6 does not have does not support block scope (where a set of braces {} defines a new scope).
A variable that is declared inside a JavaScript function, is called local variable. A local variable is created and destroyed every time the function is executed, and it cannot be accessed outside the declaring function.
<script>
if (true) {
var x = 2;
}
console.log(x); // 2, since javasript doesn't has block scope
function myFunction() {
var y=5; //local variable
console.log(y); //5
}
console.log(y); //undefined, since y is local variable
</script>
A variable that is declared outside a JavaScript function, is called global variable. A global variable is created when web page is rendered and destroyed when web page is closed. A global variable value is accessible and modifiable throughout your program.
<script>
var x=2; //global variable
if (true) {
console.log(x); // 2
}
function myFunction() {
var y=5; //local variable
console.log(y); //5
console.log(x); // 2, since x is a global variable
}
</script>
All global variables are attached to global object window, so you can set and access global variables using the window.variable syntax.
<script>
var x=2; //global variable
if (true) {
console.log(x);
//OR
console.log(window.x); //using window object syntax
}
x=6;
//OR
window.x=6; //setting value
</script>
A variable which is not declared, but has value, is automatically become global variable. It may be inside or outside a JavaScript function.
<script>
function myFunction() {
y=5; //automatic global variable
console.log(y); //5
}
console.log(y); // 5, since y is a global variable
</script>
I hope, now you have better understanding of JavaScript variable scopes. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.