How to use a return value in another function in Javascript?
Call the function and save the return value of that very call.
function firstFunction() {
// do something
return "testing 123";
}
var test = firstFunction(); // this will grab you the return value from firstFunction();
alert(test);
You can make this call from another function too, as long as both functions have same scope.
For example:
function testCase() {
var test = firstFunction();
alert(test);
}
Demo
You could call firstFunction
from secondFunction
:
function secondFunction() {
alert(firstFunction());
}
Or use a global variable to host the result of firstFunction
:
var v = firstFunction();
function secondFunction() { alert(v); }
Or pass the result of firstFunction
as a parameter to secondFunction
:
function secondFunction(v) { alert(v); }
secondFunction(firstFunction());
Or pass firstFunction
as a parameter to secondFunction
:
function secondFunction(fn) { alert(fn()); }
secondFunction(firstFunction);
Here is a demo : http://jsfiddle.net/wared/RK6X7/.