开发者

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


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.


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.


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

}


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


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
}


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜