Why do some scripts use returns instead of if statements?

(I don’t know if this is the right category)

I’ve seen a lot of people do something like this in their code:

local bool = true

function checkbool(bool)
	-- we want to check if the bool is true
	if bool == false then
		return
	end
    print("Bool is equal to true")
end

Instead of just doing

local bool = true

function checkbool(bool)
        -- we want to check if the bool is true
	if bool == true then
		print("Bool is equal to true")
	end
end

Just a question.

This is the correct category.

The return will stop the rest of the function from running. This is good if the bool variable will cause the function to error. I believe the official name for this technique is known as a “guard clause”.

It’s usually cleaner to use returns instead of an if statement that wraps around the entire function body as it doesn’t indent the function.

Leading to more readable code.

It’s a personal preference, some say it looks cleaner. It avoids indentation.

So its just for the sake of readability

From what I read on wikipedia, yeah pretty much.

Both do the exact same thing, the only difference is in the first function after the return, nothing will run, and the function will be exited. In the second function, however, things below the if statement will still continue to run.

This is called the “guard clause”, improving readability and decreasing the chances of creating spaghetti code. I advise you to use them as well.
(Plus, it also decreases the chances of some bugs appearing in your code)

What everyone else stated is correct. This also prevents you from having to constantly type extra things such as doing absolutely nothing besides printing something if you hate having empty spaces like I do. I just looked into returning just today, and I can confirm that what everyone else is saying is true. It can also be used for returning Instances back to their original variable too, I think. That last part might not be true. Correct me if I’m wrong.

IsAFriend = nil
local Friend = script:FindFirstChild("Jack")
if not Friend then
    return IsAFriend
end
1 Like

This is an excellent video on the topic.