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

11

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;
}

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 using these return within the code? I have this doubt because I did the test and took out the return and apparently the function worked normally, what would be the difference between using or not using return ?

    
asked by anonymous 30.09.2015 / 18:19

1 answer

11

In general, you can use somewhere that expects a function to return success or failure of the operation, ie a boolean . If the function is used where it does not need a specific result it does not matter and does not cause problems.

In this specific 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 that is not the intention.

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

In appearance there is nothing wrong, but depending on how you handle it, it may not work as expected.

The return in HTML is unnecessary.

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

30.09.2015 / 18:23