fmc
fmc

Reputation: 490

What are the benefits of including a return statement in a function?

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:

getAnswer(answer);

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;
    $('#ran1').html(ranNum1).show();
    $('#plus').html("+").show();
    $('#ran2').html(ranNum2).show();
    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");
    $('#captcha').focus();
    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?

Upvotes: 2

Views: 357

Answers (2)

piglovesx
piglovesx

Reputation: 82

I think you should avoid using Global Variable. As a a global variable, you maybe change it often, and difficult to debug with global variable.
Try to understand closure in Js is also helpful.:)

Upvotes: 0

aso
aso

Reputation: 1316

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() {
  showQuestion();
}

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?

Upvotes: 1

Related Questions