views:

90

answers:

5

I have some Javascript code that needs to end with either a true or false value being returned. However, when the true/false value is computed, the original value has passed through multiple functions, like so:

var txt = 'foo'    
function one(txt) {
if(txt == 'foo') { two(txt); }
}
function two(txt) {
if(txt == 'foo') { three(txt); }
}
function three(txt) {
if(txt == 'foo') { return true; }
else { return false; }
}

Obviously this example has little point but it gets the general point across. What I need to do to it is return the true (or false) value from function three() all the way back to function one(), and then have function one() return that value to whatever called it. I am assuming I have to go back through function two() to get back to one, is there a way I can do this with a variable? Just an idea. Thanks very much for any help!

+2  A: 

Change the calls to three() and two() to return three() and return two().

dhorn
That would still return undefined if you pass something other than `foo` to the `one()` function.
Daniel Vassallo
+3  A: 

You may want to try the following (if I understood your question correctly):

function one(txt) {
   if(txt == 'foo') return two(txt);
   else return false;
}

function two(txt) {
   if(txt == 'foo') return three(txt);
   else return false;
}

function three(txt) {
   if(txt == 'foo') return true;
   else return false;
}
Daniel Vassallo
Why does `|| false`?
Fabio F.
You can coerce to boolean - `return two( new Boolean(txt) );` or `return two( !!txt );` - without needing the `|| false`.
Gabe Moothart
@Fabio: I removed the `|| false` part. It isn't needed if all functions return either true or false.
Daniel Vassallo
A: 

Try:

var txt = 'foo'    
function one(txt) {
if(txt == 'foo') return two(txt); 
 else return false;
}
function two(txt) {
if(txt == 'foo')  return three(txt); 
 else return false;
}
function three(txt) {
if(txt == 'foo')  return true; 
else return false; 
}
Josh K
`one` and `two` also need `else` cases, or they won't return anything when the condition is false.
tzaman
A: 

If you like ternary operators:

function one(txt) {
    return (txt == 'foo') ? two(txt) : false;
}
function two(txt) {
    return (txt == 'foo') ? three(txt) : false;
}
function three(txt) {
    return (txt == 'foo');
}
tzaman
A: 

You can do it like people said above, or you can declare a variable outside the functions so it is global and just refer to it. It is not considered great practice, but it will work.