What Are The Benefits Of Including A Return Statement In A Function?

- 1 answer

I made up a simple CAPTCHA using JQuery. And while it works fine, I don't think I'm doing it the right way.

When the page loads, the function is called:


Which is:

function getAnswer() {  
    var min = 0;
    var max = 50;
    var ranNum1 = Math.floor(Math.random() * (max - min + 1)) + min;
    var ranNum2 = Math.floor(Math.random() * (max - min + 1)) + min;
    answer = ranNum1 + ranNum2;

And when I compare answer to the user's input:

if(answer != captcha) {
    $('#captchaErr').html("CAPTCHA is Incorrect").show().delay(3000).fadeOut("slow");
    return false;

it works. But in looking at a lot of Q&A regarding this here on SO, it seems like I should include a return statement in the function, which also works.

Since it works both ways, what are the benefits and drawbacks of including the return statement?



You don't need to return any value.

First of all, rename your function to showQuestion or something; as name suggest, it only shows question and it's not getter. answer variable should be stored somewhere - not recommended is global variable, but you can pack ran1, plus and ran2 into one DIV, and set data field:

$(document).ready(function() {

Last line in showQuestion:

$('#question').data('answer', answer);

OR you can leave function name like getQuestion(), return correct answer and set it in ready() function.

When you want to validate, simply get answer:

var answer = $('#question').data('answer');

Note that's local variable, not global.

Of course you know that captcha can't be client-side?