-2

I know this must have been asked before as it is a very simple question, however I cannot get a clear answer.

How do I get the value of a variable from a function in to another function?

var x = 0;
function firstFunc(){
    x = 1
}

function secondFunc(){
    alert(x);
}
  

Thank you

Ed Corke
  • 9
  • 3
  • 1
    It is not clear what you are asking... In your actual case, since your variable is globally scoped, it is modifiable and possible to get within both functions.. – Ulysse BN Aug 19 '17 at 17:57

6 Answers6

1

Exactly like you did. You declared x at the scope of the entire script, so other functions can evaluate it.

Calling both functions in the snippet below shows that the variable was changed by function 1 and evaluated with its new value at function 2:

var x = 0;
function firstFunc(){
    x = 1
}

function secondFunc(){
    alert(x);
}
firstFunc();
secondFunc();
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
  • Apologies and thank you...realised it was an issue in my other code that was not working. Sorry for wasting your time haha – Ed Corke Aug 19 '17 at 18:27
0

You are already getting the value of "x" across both functions. You are just not calling the functions to prove it.

Take a look at this article for more information on global variables

var x = 0;
function firstFunc(){
    x = 1
}

function secondFunc(){
    alert(x);
}
firstFunc();
secondFunc();
Assafi Cohen-Arazi
  • 837
  • 10
  • 30
0

You have several ways to do that one of them is making the first function return the variable and in the second function you can use this variable

var x = 0;
function firstFunc(){
    return x = 1
}

function secondFunc(){
    x= firstFunc();
    alert(x);
}
wahdan
  • 1,208
  • 3
  • 16
  • 26
0

Do you mean to get a local variable declared inside the function scope? if so, one way is to call the function inside a function, so we get the variable declared inside the function scope.

x = 0;
function firstFunc(){
   var x = 1;
   secondFunc();
}

function secondFunc(){
   alert(x);
}
Karthik Samyak
  • 467
  • 2
  • 8
  • 19
0

Are expecting alert should show 1 ?? This already working like that only. Check this link

http://ztoi.blogspot.in/2017/08/get-value-of-variable-from-function-for.html

Karthick Aravindan
  • 1,042
  • 3
  • 12
  • 19
0

With your current code, you are already able to get the value of the variable x across both functions.

This is possible because the x is defined as global so it can read and set by both functions.

Interesting question to learn more about js scope.

var x = 0;
function firstFunc(){
    x = 1
}

function secondFunc(){
    alert(x);
}

firstFunc();
secondFunc();
GibboK
  • 71,848
  • 143
  • 435
  • 658