Javascript return statement

Hi,

I've only recently started learning javascript and it would be helpful if someone could explain the return statement in plain english.

For an instance, let's say I have this code:

class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}

In the javascript tutorial/explanation it says: "At any time in a method the return statement can be used to cause execution to branch back to the caller of the method."

But what/who is a caller of this method? :)

Thanx.

First, that code is not JavaScript; where did you get it? Let's try to turn it into something that would work in Unity:

import UnityEngine.Debug;   // Lets us type "Log" instead of "Debug.Log"

function Start () {
    var t = true;
    Log("Before the return.");
    if (t) return;

    // No further code can execute after the return statement.
    Log("Useless code here.");  
}

Now, in that case, we used Start; which is automatically called by Unity. Let's call another function, from Start, and see how return can actually be useful:

import UnityEngine.Debug;

var kittyIsHappy = false;
 
function Start () {
    MakeSureKittyIsHappy();
    MakeSureKittyIsHappy(); // No feeding or petting happens this time.
    Log("We double-checked, so the kitty is surely happy now!");
}

function MakeSureKittyIsHappy () {
    if (kittyIsHappy) return;

    FeedKittyAHamster();
    PetKitty(); // You will be petting the kitty on a belly full of hamster! :-D
    kittyIsHappy = true;
}

function FeedKittyAHamster () {
    Log("You feed an extremely cute hamster to the kitty.");
}

function PetKitty () {
    Log("You pet the kitty on his belly.");
}

In that case, MakeSureKittyIsHappy was called, and all of the code in it was run. The execution then branched back to Start. MakeSureKittyIsHappy was called again, in Start, at that point, but only the first line was run, and execution then branched back to Start the return statement functioned as a way to avoid running unecessary code.

Alternative versions of that function, that do the exact same thing, are:

function MakeSureKittyIsHappy () {
    if (kittyIsHappy) return;
    else {  
        FeedKittyAHamster();
        PetKitty();  
        kittyIsHappy = true;
    }
}

function MakeSureKittyIsHappy () {
    if (!kittyIsHappy) {      
        FeedKittyAHamster();
        PetKitty();  
        kittyIsHappy = true;
    }
}

Often, return statements can be used to eliminate else statements and brackets. Do whatever is easiest to read, to you. I prefer the first of the three examples (with no brackets), in this case. However, as displayed, I tend to put a blank line after my return statement, to signify that it represents an important ending. You'll figure out helpful coding style as you go along.