jchand
jchand

Reputation: 827

How to access variable from other function in javascript

I have one variable in function, I want to access it from other function. I cannot define this variable out of function. I set the example code for review. http://jsfiddle.net/VC6Wq/1/

function one(){
var zero= 500;
}

function two(){
alert(zero)
}

Upvotes: 1

Views: 188

Answers (6)

anmarti
anmarti

Reputation: 5143

Since you cannot define the variable globally, one approach is simulate a global variable, attaching it to a DOM node, like this:

//note the notation 'data-'
<div id="node" data-zero='500'/>

To set the value:

   // Store the value into data var within the div
   $('#node').data('zero', value);

To get value:

   var value =  $('#node').data('zero');
   alert(value);

Example: http://jsfiddle.net/VC6Wq/4/

Upvotes: 0

Mandeep Pasbola
Mandeep Pasbola

Reputation: 2639

Try this :

function one(){
var zero = 500;
return zero;
}
function two(){   
alert(one());
}
two();

Or define any other variable globally and assign it the value of the 'zero' :

var zero_2;
function one(){
var zero = 500;
var zero_2 = zero;
}
function two(){   
alert(zero_2);
}
two();

Upvotes: 0

K D
K D

Reputation: 5989

You can declare that variable globally in Javascript and then use/modify/access as needed

function one()
{
   myVar = 0;
   alert(myVar);
   two();
}

function two()
{
  alert(myVar);
}

Upvotes: 0

Bhushan
Bhushan

Reputation: 6181

I think this is what you are looking for.

function one() {
var zero = 500;
two(zero);
}

function two(a) {
alert(a);
}

Upvotes: 10

GautamD31
GautamD31

Reputation: 28763

Try like this

function one(){
    var zero= 500;
    return zero;
}

function two(){
    var alt = one();
    alert(alt);
}

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249113

You can make your variable underneath the window global variable, if this is in a browser. So like this:

function one() {
  window.zero = 500;
}

function two() {
  alert(window.zero)
}

Upvotes: 4

Related Questions