Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return statements at the end of a JavaScript function

Tags:

javascript

I have seen in many times in JavaScript code people add a return true at the end although not necessary. Does anyone know why?

var _globalString;
function doSomething()
{
    _globalString= _globalString +' do something';
    //some codes to do something more

    //finally adding a return true
    return true;
}
like image 901
Praveen Prasad Avatar asked Mar 05 '10 10:03

Praveen Prasad


2 Answers

The thing that may have gotten some people into the habit was event handlers for forms, if you have, say:

<form onsubmit="return myfunction();">

and myfunction() returns true, the form submits, else if it returns false it doesn't. People doing it in general could've got the habit from this. Some languages require return values from functions, Javascript doesn't; and having return true at the end of most functions serves no purpose.

like image 72
Erik Avatar answered Sep 28 '22 08:09

Erik


In addition to Erik's answer I would like to add

return true / return false are also used when you want boolean value as a return. And based on that return you execute some other function.

like image 25
Nazmul Avatar answered Sep 28 '22 08:09

Nazmul