Skip to main content

Var in JavaScript

var keyword in JavaScript

The var statement is used to declare(Create) a variable. Until ES2015, var was the only only way to declare variable. Now there are two more options to declare variable: let and const.

Variables declared with var keyword have functional scope variable, This means whenever a variable is created with var in a function, it will only exist within the function.

# Declare variable

Let’s see the syntax of var keyword :

 ➤ Syntax :

<script>
    var variable_name = value;
</script>
Parameter :
  • var: JavaScript reserved keyword.

  • var_name : Name of variable.

  • value : Optional, Initial value assign at the time of declaration.

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

Let’s see the example of var keyword in JavaScript :

 ➤ Example :

    In this example, apple, mango, and totalFruits are variables.

<script>
    var apple = 8;
    var mango = 9;
          
    var totalFruits = apple + mango;
    document.write(totalFruits);
</script>
Output :

17



Scope of var keyword ?

1.) Global scope :

  • Using var keyword to define variable globally. Once you define globally, you can access anywhere inside your code.

 ➤ Example : Variable scope globally;

<script>
    var x=1; //'x' is gloabal variable
     console.log("Start program :",x);
    function display()
     {
        for(x= 1; x< 5; x++ )
         {
          console.log("Looping time :",x); // x visible on here
         }
         console.log("Inside function :",x); // x visible
     }
     display(); //calling JavaScript function
     console.log("End program :",x); // x visible
</script>

2.) Local scope :

  • Using var keyword to define variable locally (local scope). It can't be accessed or modified outside the function declaration, Function parameters are always local to that function

 ➤ Example : Variable scope within function;

<script>
   function display()
     {
       var a =10;
       console.log("Inside function : "+a);
     }
     display();
    // Uncaught ReferenceError: a is not defined
     console.log("outside function : "+a);
</script>

3.) Block scope :

  • Using var keyword, If you declare variable inside the block{ } statement, the variable can be accessed from outside the block.

 ➤ Example : Variable scope within block;

    Variables declared with the var keyword are not Block Scope.

<script>
  var age = 22;
  if (age > 21)
    {
      var name ="Ankaj Gupta";
      console.log("Inside block, name : ",name);
    }
    console.log("Outside block : ",name);   //name visible on here
</script>

# Variable Hoisting :

Variables declared with var are hoisted to the top of the enclosing function scope. If the variable is accessed before variable declaration, it evaluates to undefined.

Let's try to create an exaple :

 ➤ Example :

    Variables declared with var keyword are hoisted.

<script>
    console.log(name); //undefined
    var name = "Ankaj";
</script>

 ➤ Read more :

Read more about Variable Hoisting : Click Me


Important point's of var keyword in JavaScript :

  • Variable use without initialization : The var statement creates and initializes variables inside the scope. If you don't assign variables value at the declaration time, By default JavaScript automatically a assigns the undefined value.

 ➤ Example:

    A variable declared without a value will have the value undefined.

<script>
    var name;
    document.write(name); //undefined
</script>
  • Block-scope : Variables declared with the var keyword are not Block Scope.

 ➤ Example :

<script>
    for(var i=0; i<=5; i++ )
    {
      //write something
    }
    document.write(i); //Output :6
</script>
  • Variable Re-declaration : You can declare the same variable more than one time and also can be updated/modified.

 ➤ Example : Redeclaration of variable;

<script>
    var fruitsName = 'Apple';
    var fruitsName = 'Mango';
    console.log(fruitsName); //Output : Mango
</script>
  • Variable value Re-assigned : Variable data store in memory, which can later be accessed and modified (reassigned a new value).

 ➤ Example : Assigned a new value in given variable;

<script>
    // Assign value to x variable
    var x=10;
    //Reassign variable with a new value
    x = 20;
    console.log(x); //Output : 20
</script>
  • Dynamic type : Variables declared with var keyword are dynamic typing mean that, they can change from one data type to another data type.

 ➤ Example : Dynamic type variables;

    In this example, the variable myName change from string to number and then boolean.

<script>
    var myName = 'Ankaj Gupta';  //Ankaj Gupta
    myName= 100; //100
    myName= true; //true
</script>
  • When using var local scope is within a function, means that a variable with the same name can be used in two separate functions, because each is recognized only by the function in which it is declared.

 ➤ Example :

<script>
    function myFunction()
     {
       var data = "I am local scope";
       document.write(data); //Output: I am local scope
     }
    function display()
     {
       var data = "I am  also local scope";
       document.write(data); //Output: I am also local scope
     }
    myFunction();
    display();
</script>

Comments

Popular Posts

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...

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 ? 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 ...