tags:

views:

74

answers:

5

i have seen in many javascript codes ppl add a "return true" at the end althouhg not necessary anybody know y??

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

//finally adding a return true
return true;
}

//
+5  A: 

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. False and it doesn't. People doing it in general could be habits from this, or possibly other places. Some languages require return values from functions. Javascript doesn't and having return true; at the end of most functions serves no purpose.

Erik
i was aware of the form thing but still thanx for clarifying the fact.
Praveen Prasad
A: 

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

pavun_cool
A: 

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.

Hoque
yaa that's obvious
Praveen Prasad
A: 

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?

Tobias Cohen
A: 

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... */

}
Bren G.