Skip to main content

Variable Scope in JavaScript

What is Scope ?

Scope in JavaScript defines accessibility of variables, functions and objects.

It defines the lifetime and visibility of a variable, Every time we create a function or a block {} , we create a new scope.

Variable Scope :

Variable scope is the accessibility of variables, objects, and functions in some particular part of your code during runtime. In other words, scope determines the visibility of JavaScript variables and other resources in areas of your code.

Scope is how a computer keeps track of all the variables in a program, It refers to the specific environment where a JavaScript variable is accessible and can be used.

In JavaScript, there are 3-types of variable scope :

  1. Global variable - Global variable are those declared Globally(outside any function).

  2. Local variable - Local variable are those declared locally(Inside any function or Block).

  3. Lexical variable - Lexical scope is the ability of an inner function to access the scope of an outer function.

Note : Global variables can be accessed from anywhere in a JavaScript program.

1.) Global variable :

  • A global variable has global scope. Which means, it can be defined anywhere in your code.

  • JavaScript global variable is declared outside the function or declared with window object and it can be accessed and modified from anywhere in code.

  • Global variable always stored in memory even function execution finish, it always keep in memory or always accessible from anywhere in JavaScript code.

Let’s see the example of global variable in JavaScript:

  ➤ Example 1: Variable defined outside any function;

In this example below, we will create a global variable.

<script>
    //Initialize a global variable
    var data=100; //'data' is global variable
    function myFunction(){
      document.writeln(data);  // here can use data
    }
    function display(){
      // can also use data
    }
    myFunction(); //calling JavaScript function
</script>

When you declare a javascript variable outside the function, it is added in the window object internally. You can access it through window object also.

  ➤ Example 1.2: Variable access with window object.

<script>
    var data=100; 
    function display()
     {
       document.writeln(data);
       document.writeln(window.data);
     }
    display(); //calling JavaScript function
</script>

Declaring JavaScript global variable within function / Internals of global variable in JavaScript

  • To declare global variables inside function, you need to use window object.

  • Now it can be declared global variables inside any function and can be accessed from any function.

  ➤ Example 1.3: Global variable defined inside any function;

<script>
   function myFunction(){
      //declaring global variable by window object 
      window.data=100;   
   }
   function display(){
      //accessing global variable from other function
      document.writeln(window.data);
   }  
   myFunction();  //calling JavaScript function
</script>

When you declare variables if you are not specify, like : var keyword, automatically variable can consider global scope.

  ➤ Example 1.4: Auto global scope.

<script>
   function display()
     {
       //variable declaring without specify keyword
       data=100;
       document.writeln(data);
     }
    display();
    document.writeln(data);  //data is accessible on here
</script>
Output :

100

100


2.) Local variable :

  • A variable declared inside function is a local variable.It is usable only in a specific part of your code are considered to be in a local scope.

  • Local variable have local scope, It can't be accessed or modified outside the function declaration, Function parameters are always local to that function.

  • Local variable store in stack frame within function, while function start execution and removed from memory once it done with execution.

  • In JavaScript, there are 2-kinds of local scope :-

      i.) Function scope

      ii.) Block scope

Note : Local variables are created when a function starts and deleted when the function ends.

i.) Function scope :

  • Variables declared inside a function is known as Function scope. In JavaScript, Each function creates a new scope.

  • When you declare a variable within a function, the variable can accessed within that function. When you exit the function the variable is destroyed, that means they can’t be accessed from the outside function code.

Let's see an examples of function scope :

  ➤ Example: function scope;

<script>
   function myFunction()
     {
       var data = "I am local scope";
       document.write(data);
     }
     myFunction();
     document.write(data); //Uncaught ReferenceError: data is not defined
</script>

Note : Javascript functions have their own scope, But blocks scope such as :(if and switch conditions or for and while loops) do not.

ii.) Block scope :

  • A block scope variable is similar to a function scope, but is limited to a block instead of a function. Block is separated by curly braces { and }.

  • ES6 introduced const and let variables, unlike var variables. Both keywords allow us to scope to a block of code, they can be scoped to the nearest pair of curly braces.

  • When you declare a variable between curly brackets {} with const or let, it can access this variable only within that curly brace. That means, block scope variable can’t be accessed from outside that pair of curly braces.

  • Block statements like : for and while loops or if and switch conditions unlike functions, don't create a new scope.

Let's see an examples of Block scope :

 ➤ Example :

<script>
  for(let i=0; i<=5; i++ )
    {
       //write something
    }
    document.write(i); //i can not be used here;
</script>

Note : let and const are block scoped variables. Block scope does not apply to var.

Important point of Block scope :

  • Before ES2015 JavaScript did not have Block Scope.

  • Variables declared inside a block {} can not be accessed from outside the block.

  ➤ Syntax:

<script>
    {
      let x= 2;
    }
    document.write(x);  //x can not be used here;
</script>
Output :

ReferenceError: x is not defined

  • variables declared with var keyword inside a block {} , can be accessed from outside the block.

  ➤ Syntax:

Variables declared with the var keyword can not have Block Scope.

<script>
    {
      var x= 2;
    }
    document.write(x);  //x can be used here;
</script>
Output :

2

3.) Lexical scope :

  • Lexical Scope also known as (Static scope or Nested scopes) literally means that scope is determined at the lexing time (generally referred to as compiling) rather than at runtime.

  • Static scope means When a function is defined in another function, the inner function has access to the outer function's variables. This behavior is called lexical scoping.

Syntax :

 ➤ syntax : Nested scopes;

<script>
   function myFunction()
     {
       //local function scope;
       function innerFunction()
        {
         //nested local function scope;
        }
     }
</script>
Let's see the examples of Lexical scope :

 ➤ Example :

<script>
   function myFunction()
     {
       const outer =I'm outer function!`;
       function innerFunction()
        {
         const inner =I'm  inner function!
         document.writeln(outer) 
        }
        innerFunction();
     }
    myFunction();
</script>
Output :

I'm outer function!

I'm inner function!

Why is Scope Important ?

  • The main benefit of scope is security.

  • The variables can be accessed from only a certain area of the code. Using the scope, we can avoid unintended modifications to the variables from other parts of the program.

  • It also reduces the namespace collisions occur when two or more variables share a common name.

Comments

Popular Posts

Django static files not working when debug false || debug true

# Django static and media files not working when debug is false In this article you will learn how to fix problem of not loading static files and media in Django even the DEBUG is FALSE. This is the easiest and safest solution. # Problem: Django static and media files not working when debug is false  ➤ Code: settings.py DEBUG = False #True ALLOWED_HOSTS = [ '*' ] #Host name # Problem Fix: Let's see, How you can fix the problem of Django static and media files not working when DEBUB = False : 1.)First way: devserver in insecure mode If you still need to server static locally ( e.g. for testing without debug ) you can run devserver in insecure mode: python manage.py runserver --insecure --insecure: it means you can run serve...

How to remove the date and .html from every blogger post url

#Remove date and .html from blogger post url A Common search term which every blogger search is How to Remove Date From Blogger Post URL or how do I remove date from blogger permalink? Follow the steps below and then date and .html will be removed from the URL of your blogger post. Step 1 : Login to your Blogger blog and select Theme / Template. Step 2 : Click on Edit HTML and paste the below code just above the </head> tag let's see code :   ➤ Code : mycode.js; Copy code <script type='text/javascript' > //<![CDATA[ // BloggerJS v0.3.1 var urlTotal,nextPageToken,postsDatePrefix=!1,accessOnly=!1,useApiV3=!1,apiKey="",blogId="",postsOrPages=["pages","posts"],jsonIndex=1,secondRequest=!0,feedPriority=0,amp="&"[0];function urlVal(){var e=window.location.pathname,t=e.length;return...

How to remove ? m=1 or ?m=0 from blogger post URL

# Remove m=1 From URL of Blogger post A Common search term that every blogger search is How to ?m=1 or ?m=0 from blogger Post URL. We all know that "simplicity is beauty" and you want to clean permalink. So, in this article, I will guide you on how to remove ?m=1 from the blogger URL, and make a simple professional URL. Follow the few steps below and removed ?m=1 from the URL of your blogger post. Step 1 : First, you login into your blogger's dashboard and then select your blog. Step 2 : Click on the Theme option. Step 3 : Click on the customise Step 4 : Click on Edit HTML option. Step 5 : Press (CTRL + F) from the keyboard and type "/head" and then search. ( If you are not understanding, see the below photo ) Step 6 : Now paste the below code just above the </head> tag. let's see code :   ➤ Code : mycode.js; Copy code ...