0

I have a global variable a and I am using it inside a function and assigning a value to it. When I use this variable outside the function it gives me undefined.

Eg.:

var a;
function my_func(){
  a=5;
}
console.log(a); //outputs undefined, how do I get the value 5 here

Why do I get undefined instead of 5?


It dint resolve my issue.

var id;

function set_id(myid){
 id=myid;
}

function get_id(){
 return id;
}

$("#btn").click(function(){
 $.post("....", function(data){ //data reurns a JSON
  set_id(id); //success!!
 }
}

$("#show").click(function()[
 console.log(get_id()); //doesn't work, how do I get this workin.. Where am I going wrong
}
1
  • before consoling the variable, you need to call the function, my_func(); untill then var a will be undefined. Commented Jul 27, 2012 at 18:46

2 Answers 2

3

you should call the function my_func before log:

var a;
function my_func(){
  a=5;
}
my_func();      //<-- here
console.log(a);
Sign up to request clarification or add additional context in comments.

Comments

0
var a;

function my_function1() {
    return 5;
}

function my_function2() {
    a = 5;
}

/* Either of these options below will work to change the value of "a" to 5*/

// a = my_function1()
// my_function2()​​​

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.