As alex said, the return function transfers control out of the function call immediately; no other statements in the function (other than finally blocks) are executed.
So:
function foo(a) {
if (a == 1) {
alert("a is 1");
return;
alert("This never happens, it's 'dead code'");
}
alert("a is not 1");
}
foo(1); // alerts "a is 1" and nothing else
foo(2); // alerts "a is not 1"
Regarding what I said above that "no other statements in the function (other than finally blocks) are executed", more about finally blocks:
function foo(a) {
try {
if (a == 3) {
throw "a is e";
}
if (a == 1) {
alert("a is 1");
return;
alert("This never happens, it's 'dead code'");
}
alert("a is not 1");
}
catch (e) {
alert("exception: " + e);
}
finally {
alert("finally!");
}
}
foo(1); // alerts "a is 1", then "finally!"
foo(2); // alerts "a is not 1", then "finally!"
foo(3); // alerts "exception: a is 3", then "finally!"
Note that no matter how the execution leaves the try/catch block, either naturally by falling out the bottom, or early because of return, or early because of an exception, the code in the finally block always runs.
Off-topic: Separately, note that you need parentheses around that function expression if you're going to call it immediately like that:
var isNumberEqualOne = (function(){
// ^--- here
if(num == 1){
return true;
}
return false;
})();
// ^--- and here
or you can put the () that call it within the parens like this:
var isNumberEqualOne = (function(){
// ^--- here
if(num == 1){
return true;
}
return false;
}());
// ^--- and here
Either works.