Tuesday, May 16, 2017

Variable Scope

Hi guys, today I'm going to discuss about variable scope. You can remember, we discussed about variables in previous lesson. In here we are talking about where to use variables.

What is Variable Scope?
The scope of a variable means the region of the program where the variable is defined.
There are two scopes in JavaScript. They are,

  1. Global Variables
  2. Local Variables
Global Variables
Global variables are declared outside the function. They can be used anywhere inside the program. Let's look at an example.

Example 1

Figure 1

In here, as you can see variable 'name' is declared outside the function. Therefore it is a global variable. So, that variable can be used inside the function or outside the function. Therefore let's see the result now.

Figure 2

As you can see, in the result we got, variable has been used inside the function and outside the function. Thus it is a global variable and it can be used in anywhere in the program.

Local Variables
Local variables are declared inside the function. They are only allowed to use inside the function.
To get a better understand, let's look at an example.

Example 2

Figure 3

In here, we declared the variable inside the function. If we declare a variable inside a function, it is called local variable. Therefore, in here, variable 'name' is a local variable. Since it is a local variable, it can be used inside the function only.

Figure 4

This is the result we got. As you can see, variable 'JavaScript' is only used in first statement. Because, since it is a local variable, it is only visible within the function it is defined. Since the second statement is placed outside the function, it doesn't know what is the variable 'name' means. So, it doesn't display the value of it.

As a good programmer you must know where to use global variables or local variables. I think these examples will be helpful to you understand the variable scope.

Thank you.

No comments:

Post a Comment