Reputation: 436
I'm self-teaching myself JavaScript and out of curiosity I'm wondering what is the proper way of returning a value from one function to be used in another function. For example:
function firstFunction() {
// do something;
return somevalue
}
So how do I set up the second function to use somevalue? Thanks.
Upvotes: 19
Views: 149572
Reputation: 1
function reSult(num1,num2){
if(num1<=num2){
return num1 + num2
}
else
{
return num1 -num2
}
}
let pass= reSult(40,5);
function outPut(pass,num3){
if(pass<=40){
return pass * num3
}
else{
return pass / num3
}
}
console.log(outPut(pass,20))
Upvotes: 0
Reputation: 3108
To copy the return value of any javascript(in chrome console), we can use inbuilt copy()
method.
you can use any expression, function, etc find some examples below
a = 245; copy(a);
a = function() { return "Hello world!" } copy(a());
Official Doc for reference
Upvotes: -1
Reputation: 868
var captcha = '';
//function name one
function one(captcha){
var captcha = captcha;
//call another function and pass variable data
var captcha = firstFunction(captcha);
};
// second function name
function firstFunction(captcha){
alert(captcha);
}
Upvotes: 0
Reputation: 46900
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);
}
Upvotes: 39
Reputation:
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/.
Upvotes: 3
Reputation: 2562
You can do this for sure. Have a look below
function fnOne(){
// do something
return value;
}
function fnTwo(){
var strVal= fnOne();
//use strValhere
alert(strVal);
}
Upvotes: 0
Reputation: 2375
Call function within other function :
function abc(){
var a = firstFunction();
}
function firstFunction() {
Do something;
return somevalue
}
Upvotes: 0