Introduction
This is the Advanced JavaScript article series, this series explains many topics of JavaScript. We have covered many important concepts here; please visit those links to understand them.
- Advance JavaScript: History and role of JavaScript behind modern web
- Advance JavaScript: play with object in JavaScript
- Advance JavaScript: Function Definition Style in JavaScript
- Advance JavaScript: Understand undefined in JavaScript
- Advance JavaScript: Understand "class"-ical concept of JavaScript
- Advance JavaScript: Implement inheritance in JavaScript
- Advance JavaScript: Callback design pattern and callback function in JavaScript
- Advance JavaScript: Exception handling in JavaScript
- Advance JavaScript: Scope of Variable in JavaScript
- Advance JavaScript: closure in JavaScript
In this article, we will learn about the various scopes of variables in JavaScript. I hope we all know the basic concepts of scope in programming languages. In general thin, we implement scope to protect and separate our data. Actually scope creates a block in an application. Within this block we can perform our local operations without affecting the code of some other portion. In JavaScript, we obviously create scope and declare a variable (and code) within it. We will now see the accessibility of variables in scope. There are generally three kinds of scopes. We will see them one by one with examples.
When we declare a variable within a function the scope of the variable becomes that function. If we try to access it outside the function, it will not be accessible. In the following example, we are trying to access "b" outside of fun1(), where "b" is defined within fun1().
So, for the purpose of the function's scope, the accessibility of the variable is within this function only. From outside of that function it will not be accessible.
This is a very well known and common scope in program development. In JavaScript, if we declare a variable within a block then it will be accessible from outside of that block. Try to understand the following code.
We are seeing that, "b" has been defined within one block ({} brackets) and from outside of the block, it is accessible. Here is sample code for the same.
Function scope

Block scope

- <form id="form2" runat="server">
- <script>
- var a = 10;
- {
- var b = 100;
- }
- var c = a + b;
- alert(c);
- </script>
- </form>

Nested function scope
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- </head>
- <body>
- <form id="form2" runat="server">
- <script>
- var value1 = function () {
- var a = 100;
- var value = function () {
- alert("Value of a is:- " + a);
- }
- value();
- };
- var abc = value1();
- </script>
- </form>
- </body>
- </html>


Comments
Join the conversation! Your thoughts help the community grow.