user3048785
user3048785

Reputation: 45

How to acces variable from one function to another in javascript

I want to access the value of variable a inside var2() function. However, it gives an error saying the value is not defined.

<html>
<head>
<script type="text/javascript">
  function var1(data) 
     {
        var a = data;
     }

  function var2() 
     {
        var b = a;
        alert(b);
     }
 </script>
 </head>
 <body>
    <a href="#x" class="overlay" onclick="var1(data)"></a>  
    <input type="button" value="Send" onclick="var2()"  />
 </body>
 </html>

Please anyone help me.

Upvotes: 3

Views: 461

Answers (6)

t.niese
t.niese

Reputation: 40842

While you already have accepted an answer I need to mention that it is generally a bad idea to define something in the global space (no matter if it is a variable or a function).

The problem with the global scope is that there are already many things defined by the browsers. In current browsers 500+ variables, definitions and function are defined there and there is a high risk in naming conflicts. If there is a name conflict with your variable name and an already defined one the results can be unexpected and hard to debug (common pitfalls are top, pos, parent, name, self, title). The problem is that they either influence the behavior of your browser or that they are readonly and you would not be able to store anything inside of them.

If you change your example to use the name top instead of a and you define it in the global scope your could would probably look like this:

 var top;

 function var1(data) {
   top = data;
 }

 function var2() {

   var b = top;
   alert(b);
 }

 var1(1000);
 var2();

You now would expect that alter(b) is 1000 but it is (depending on the browser) [object Window] because top is readonly and will still reference to the top window.

If you think over using the name location then it is way worser and your page will be redirected to a new location.

The same problem is for functions if you name one of your function with a name already used by the browser in the global scope (no matter if it is a variable or a function) you would get an error like:

Uncaught TypeError: function '....' has already been declared

So you would need to check every browser in every version you want to support, if these variables are protected. And even then you would not know what is introduced for future versions. So you should always try to avoid to write something in the global scope as much as possible.

A solution that would avoid to have write something in the global space would look like this (using jQuery to attache the events because you mention it in your tags)

 <script type="text/javascript">
 /* define an anonymous function and directly call it
    that param '$' is used to alias jQuery to a short name, 'undefined' is used
    to be sure that it is really undefined
    ('undefined'  is not a protected keyword and could have been overwritten)
 */
 (function($, undefined) {
     var a; /* limits the visibility of 'a'  to the scope of the
               anonymous function (not visible in the global scope) */

     /* defines the function 'var1' in the scope of the anonymous 
        function (not visible in the global scope) */
     function var1(data) 
     {
       a = data;
     }


     /* defines the function 'var2' in the scope of the anonymous
        function (not visible in the global scope) */
     function var2() 
     {
       var b = a;
       alert(b);
     }

     /*
     because the functions 'var1'  and 'var2'  are not 
     visible in the global scope you need define the 'click'
     handlers from within this scope.
     */


     /*
     Register the click events using event delegation.

     So for every element with the attribute 'data-action="call-var1"' var1(data)
     is called and the same for 'data-action="call-var2"'
     */
     $(document).on('click', '[data-action="call-var1"]', function() {
       var1(data); // I don't know what 'data' is in your example
     });

     $(document).on('click', '[data-action="call-var2"]', function() {
       var2();
     });

  })(jQuery); /* we pass jQuery as parameter when calling the anonymous
                 function for the case '$' is not not jQuery */
  </script>
 </head>
 <body>
    <a href="#x" class="overlay" data-action="call-var1"></a>  
    <input type="button" value="Send" data-action="call-var2"  />
 </body>

Upvotes: 0

RMsplace
RMsplace

Reputation: 53

First declare the variables before making a function:

jsfiddle

var a = "test";
function var1() {
    document.getElementById('data').value = a;
}

function var2()  {
    var b = a;
    alert(b);
}

Upvotes: 0

TW80000
TW80000

Reputation: 1505

This is because of the scope of the variables. This means that variables inside functions are not accessable to other functions that are on the same or a higher level. Functions can however use variables that have been made at a higher level.

If you want to access that variable, try returning it.

function var1(data) {
    return data
};

function var2() {
    var b = var1("This string is a"); // b = "This string is a"
    alert(b);
};

In this context, doing this makes no sense though.

Upvotes: 0

Cyclotron
Cyclotron

Reputation: 339

It's a question of scope. The way you have it in your code, a's scope is only within function var1. You need to define it outside the scope of the function for it to be available to other functions:

var a;
function var1(data) 
 {
   a = data;
 }

Upvotes: 1

Oki Erie Rinaldi
Oki Erie Rinaldi

Reputation: 1863

I think you should declare the variables as a global variable first, so you can access it anywhere.
Here it is:

<html>
<head>
<script type="text/javascript">
var a,b;
  function var1(data) 
     {

       window.a = data;

     }

  function var2() 
     {

        window.b = window.a;
        alert(window.b);
     }
 </script>
 </head>
 <body>
 <a href="#x" class="overlay" onclick="var1(data)"></a>  
 <input type="button" value="Send" onclick="var2()"  />
 </body
 </html>

Try it! :D

Upvotes: 3

Indranil.Bharambe
Indranil.Bharambe

Reputation: 1498

try below code

var a;
function var1(data) 
 {

    a= data;

 }



function var2() 
 {

    var b = a;
    alert(b);
 }

Upvotes: 3

Related Questions