views:

73

answers:

3

Hi,

Given is the following code:

function two() {
    return "success";
}

function one() {
    two();
    return "fail";
}

If you test the code by calling function one(), you will always get "fail".

The question is, how can I return "success" in function one() by only calling function two()?

Is that even possible?

Regards

+6  A: 
function one() {
   return two();
}
jAndy
+2  A: 
function one() {    
    return two();
}
+4  A: 

You can't make a function return from the function that called it in Javascript (or many other languages, afaik). You need logic in one() to do it. E.g.:

 function one() {
     return two() || "fail";
 }
andrewmu
Thats plain wrong, "success" || "fail" will fail, neither are boolean
smirkingman
It's not wrong. According to the rules of JavaScript, as written by the Ancients of the Web, an or operator (`||`) will return the first argument if it does not evaluate to a 'falsy' value (e.g. false, undefined, null, 0, ""), otherwise it will evaluate and return it's second argument.
andrewmu
@smirkingman Actually, you're wrong. A string evaluates to a true boolean value in JS. Punch `"success" || "fail"` into any JS console and it will return `"success"`. Know what you're talking about before you bash someone's response.
mattbasta
Also, +1 to andrewmu for coming up with a creative response!
mattbasta
And restore my rating to 0 while you're at it!
andrewmu
Apologies. Edit: Damn, it won't let me undo the -1 and it won't let me +1. Can you edit the answer so I can change it back?
smirkingman
Thanks. Downvote now removed.
smirkingman