1

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)
}
5
  • 1
    Why not pass zero as argument to two? Why you can not define it globally? Commented Feb 19, 2013 at 12:59
  • can we use .get or json for this requirement Commented Feb 19, 2013 at 13:01
  • You may attach this variable to a DOM node using the jQuery data() like <div id="node" data-zero='myvalue'/> method. Then accessing to its value using $('#node').data('zero'); Commented Feb 19, 2013 at 13:03
  • can you please set an example with data method Commented Feb 19, 2013 at 13:19
  • Hope this helps you. jsfiddle.net/VC6Wq/4 Commented Feb 19, 2013 at 14:34

6 Answers 6

10

I think this is what you are looking for.

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

function two(a) {
alert(a);
}
Sign up to request clarification or add additional context in comments.

Comments

4

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)
}

Comments

2

Try like this

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

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

Comments

0

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);
}

Comments

0

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();

1 Comment

I cannot define this variable out of function.
0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.