What is the purpose of the "Return true;" command at the end of a function?

Asked

Viewed 2,046 times

13

I noticed that in many functions in javascript I see at the end a return true.

function EscreveDados(){
    document.getElementById("divData").value = 'texto';
    return true;
}

and in HTML we have the tag which calls the function followed by a "Return" as well.

<form method="post" onsubmit="return EscreveDados()">
    <textarea id="divData"></textarea>
</form>

What is the purpose of the use of these return within the code? I have this doubt because I took the test and took the return and apparently the function worked normally, what would be the difference between using or not using the return?

1 answer

12


In general you can use somewhere waiting for a function that returns success or failure in the operation, ie a boolean. If the function is used where you don’t need a specific result it doesn’t matter and causes no problems.

In this particular case it is obvious that there will always be success. If it did not have this, by default it would be assumed that the return was false, that is, the validation failed, and this is not the intention.

In your case the return true is important to inform HTML that everything is ok and sending (submit) should be done normally as is the default. If returned false the browser would treat the action as a submission not to be performed, changing the default functioning.

There’s nothing wrong with appearance, but depending on how you handle it, it might not work.

The return in HTML is unnecessary.

Alias, this is a mechanism considered obsolete. It would be better to use the preventDefault, but this is not the focus of the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.