• Register
278 points
6 1

In this article, we see how to access variable outside function in javascript?

Scope in JavaScript defines accessibility of variables, objects and functions.
There are two types of scope in JavaScript.

  1. Global scope
  2. Local scope

Global Scope

Variables declared outside of any function become global variables. Global variables can be accessed and modified from any function.

<!DOCTYPE html>
<html>
   <body>
      <script>
         function loader()
         {
               profile = [];   // No "var" makes this global in scope
               profile[0] = "Kodlogs";
               profile[1] = "blogs or articles";
         }
         loader();    //Function call
         document.write("Website Name is: "+ profile[0] +"<br>We can read "+ profile[1]);
      </script>
   </body>
</html>

Output:-

Website Name is: Kodlogs
We can read blogs or articles

Local Scope

Variables declared inside any function with var keyword are called local variables. Local variables cannot be accessed or modified outside the function declaration.

<!DOCTYPE html>
<html>
<body>
	<p id="error"></p>
	<script>
        function createUserName() 
        {
			var userName = "Kodlogs";
        }
        function showUserName() 
        {
			try
            {
				alert(userName);
			}
			catch(ex)
			{
				document.getElementById("error").innerHTML = ex;
			}
        }
		createUserName();
		showUserName();   // throws error: userName is not defined
	</script>
</body>
</html>

Output:-

ReferenceError: userName is not defined
In the above example, userName is local to createUserName() function. It cannot be accessed in showUserName() function or any other functions. It will throw an error if you try to access a variable which is not in the local or global scope. Use try catch block for exception handling.

1 Comment

This article is really helpful. Thanks.