Need explanation of 'return false' inside function
I can't find it anywhere on google an explanation of what the return false can and can't stop
I'm not sure, and I don't have anywhere to confirm, other than trial and error, but I've come to the conclusion that 'return false' statements withing
Code:
function() {
doSomething()
function() {
if (true) return false
do() // won't get called
}
doSomethingAgain() // will get called
if (true) return false
doSomethingElse()//won't get called
}
If anyone can give an explanation of why this works. Also, do 'for' statements act the same way as 'if' statements, meaning that if a return false is called within a for loop, will it stop everything in that loop, AND in the function containing the for loop?
return does not affect control structures (such as conditionals/loops), it affects functions only - in Javascript anyway.
It does exactly what you think it would do - it "returns" whatever immediately follows the return statement from the function. By "return"-ing, it stops the function in it's tracks. The return statement, if executed, is always the LAST statement to be executed by a function.
In your example above, the anonymous function that is inside your function will return false (because if(true) will always be executed) to whatever variable is assigned to the function (in this case there is none). Thus, do() won't get called.
However, that return statement is inside an anonymous function and has no affect on the outer function it is contained in. The outer function returns false right before doSomethingElse() would've been called. Because return is always the last statement executed by a function, whatever follows it - doSomethingElse() - won't get executed.
Clear as mud?
I've switched careers...
I'm NO LONGER a scientist,
but now a web developer...
awesome.
Question: is it possible to in a way do a double return to stop the main function within the anonymous function?
return and not that I know of. You can only return the closure you are in, unlike with using labels and control structures. You're probably at a stage where you'd start to find doing research on closures useful too.
Great wit and madness are near allied, and fine a line their bounds divide.
Bookmarks