Praveen Prasad
Praveen Prasad

Reputation: 32107

Return statements at the end of a JavaScript function

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

Upvotes: 11

Views: 26133

Answers (6)

Jawad Anwar
Jawad Anwar

Reputation: 1

Also you do not need to use return true or false in this case below

var newPage = "http://www.google.com";
function redirectURL(){
   window.location.href= newPage;
   return true;      //no return required
}

Upvotes: 0

Erik
Erik

Reputation: 20722

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.

Upvotes: 20

Bren G.
Bren G.

Reputation: 161

A "return" inside a function automatically stops further execution of that function so for example:

function myFunc(){
    if(foo == 'bar'){
     /* do something */
    }else{
     /* do something */
    }
}

is the same as:

function myFunc(){
    if(foo == 'bar'){
        /* do something */
        return true;
    }

    /* if foo != 'bar' then whatever follows is executed... */

}

Upvotes: 3

Tobias Cohen
Tobias Cohen

Reputation: 20000

It's hard to say why some programmers do certain things.

Maybe it's intended to indicate success/failure, but they haven't added any failing branches yet?

Upvotes: -1

Nazmul
Nazmul

Reputation: 7218

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.

Upvotes: 3

Pavunkumar
Pavunkumar

Reputation: 5335

Actually if you are calling the function in onsumbit event

Example

 

<input type=sumit value=click Onsumbit='return function_name();">

While you are calling like , if the function return true only, form will be submit

If it return false , it wont submit the form

Upvotes: 0

Related Questions