Using return ... a better explanation?


#1

I've been trying to understand the return keyword as used in lesson 7/13 to 9/13, but I'm failing to see where it is of value in the sample exercises, maybe return is used for more complex calculations?
Can someone dumb-it-down for me, please? In 9/13 we would get the same answer if we just define a variable, no? I'll take a break and try to come at it from a different angle.


#2

Functions are some sort of sub programs so instead of being executed like regular code they need to be started and stopped. To start a function and to provide information to a function you use the function call and arguments e.g.

var square = function (x){
   return x*x;
}

square(2);

here square(2) would be the function call. Now this call interrupts the main program and start the square program. Now return is the opposite process you end the sub program square and return back to the calling program. A possible use of this might be that:

var complexFunction = function(input){
   if(input != ...){
      return;
   }
   ...
}

here return is used to exit the function earlier. Another use of return is that it can transport information from the function to the caller by changing the value of the function call with with the value after return. E.g. the square function function call square(2) would now have a value of x*x where x is 2 -> 4. If you want to use neither of this the interpreter will automatically add an return at the very end of your function and doesn't bother you with it.

Hope this makes it clearer.


#3

Thank-you, makes sense and it was along the lines I was thinking but the examples did not reflect this logic and that was the source of my confusion.