Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

JavaScript 010 – Local & Global Scope

1. Local Scope and Global Scope

We know that JavaScript is not strict in Type-Checking. In JavaSctipt, a variable can hold an integer and the same variable can even store string later. However, JavaScript supports variable scope and lifetime eventhough they are typeless. The Script writer should know Global Scope and Local Scope of variables and functions along with the lifetime. In this example, we will learn all these.

2. Variable Declared at Global Scope

Below example explains how Global Scope works:

Global Variables in JavaScript
Global Variables in JavaScript

1) We declared as well as initialized two variables Number1 & Number2. These two variables do not participate in the body of any Function and hance they are in Global Scope.
2, 3) In the script, we used these variables and printed it. Note, these variables can be accessed inside the functions as well. We will see it soon.
4) The output shows the content of the variables.

3. Local Scope

A Local Scope, also called as Function Scope, contains variables and functions local to a specific function. Have a look at the below example, which contains a function named AFunction:

Local Variables in JavaScript
Local Variables in JavaScript

1) Here, we declared two more variables Number1 and Number2. These two variables are local to the Function – AFunction
2) We print the Variable Number1. There are two scopes that come into picture here. Number1 declared at Global Scope (Refer previous Section) and same variable name declared inside this function, which is in LocalScope. The LocalScope variable hides the global scope and prints 5.
3) This variable in local scope prints the value 10.
4) The variable Number3 is not declared inside the function. Since it is in Global Scope, it is visible inside this function.
5) Shows the result of executing the extended script.

4. Variable Lifetime

A variable in Function Scope (Local Scope) can live until the function end. After the function body, the variable dies along with the value in it. Whereas the global variables have extended lifetime and it lives as long as the page lives. Now, have a look at the below example:

Variable Lifetime
Variable Lifetime

1) Here, we try to access the variable Number1.
2) Global Scoped variable contents.
3) Number1, Number2 and Number3 are from Local Scope and its content displayed in the browser.
4) Since Function call ends at this stage, content in Number1 is from the Global scoped variable. Hence, we see 7 in the output.

5. Code Reference

Categories: JavaScript

Tags: , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.