Javascript Local and Global variable

1. var my_number = 7; //this has global scope
2.
3. var timesTwo = function(number) {
4. my_number = number * 2;
5. console.log("Inside the function my_number is: ");
6. console.log(my_number);
7. };
8. timesTwo(7);
9. console.log("Outside the function my_number is: ")
10.console.log(my_number);

in the above piece of js code,1st line tells that my_number has a global scope.
in 4th line if you did not include var before my_number, then it act as a global scope.
it is explained detail below:
Using my_number without thevar keyword refers to theglobal variable that has already been declared outside the function in line 1. However, if you use the var keyword inside a function, it declares a newlocal variable that only exists within that function.

after including var in 4th line, then it act as a local variable which is not possible to access outside the function.

1. var my_number = 7; //this has global scope
2.
3. var timesTwo = function(number) {
4. var my_number = number * 2;
5. console.log("Inside the function my_number is: ");
6. console.log(my_number);

7. };
8. timesTwo(7);
9. console.log("Outside the function my_number is: ")
10.console.log(my_number);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s