Else or Elseif?

I have a written code for a Part in my game however, I have noticed that both elseif and else work. Which one do you recommend I use. Does it matter which one I use?

For the elseif statement I used: elseif Player.Backpack:FindFirstChildWhichIsA(“Tool”) then

In this example I just used else:

local Button = script.Parent
local ClickDetector = Button.ClickDetector

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Tool = ReplicatedStorage.Tools.Tool

	print(Player.Name .. " clicked " .. Button.Name)
	local ToolClone = Tool:Clone()
	if not Player.Backpack:FindFirstChildWhichIsA("Tool") then
		ToolClone.Parent = Player.Backpack
		print(Player.Name .. " already has a Tool in Backpack")

else is for when like if statement is wrong, it’ll do else, if elseif, it checks the another statement when the statement is wrong.

elseif allows you to check for alternative conditions if the original one wasn’t met whereas else is a catch-all if none of the conditions were met.

For the example code block you provided, using else would work fine because the original condition is only checking if the player does not have any Tools in their Backpack. If that condition was not met, that indicates that the player already has a Tool in their Backpack and it would default to either evaluating the next elseif then statement or the code inside of an else block.

If there are no other specific conditions that have not been proven by the original condition that you want to check for, using else should be suitable for that use case.


Conditional Statements Developer Hub Article


Ok thanks for letting me know. Learning something everyday :slight_smile:

1 Like

Ok thanks for letting me know. Learning something everyday. Also, thanks for showing the Resource :slight_smile:

1 Like

When you use else, it is only going to run when the if statement is equal to false. When you use an if statement in that else statement (elseif), you are checking if another thing is true, but it is only checking when the first value is false. So if you deffinetly want to run the if statement, just run another if statement.

Hope this helped you out :slight_smile:

1 Like

There actually is a slight difference!

Else is used for if a statement returned true/false, example:

local bool = true

if bool then
    print('Bool is false!')

In that code snippet, it would check if the bool is true, and if it is, it would print ‘true’. However, if it was false, it would print ‘Bool is false’!

Elseif does similar behavior but is intended for an if statement within an if statement, meaning if the first if returned false, the second (or elseif) would do the check, and if that’s true, then it continues the thread. If it returns false, it continues the code after the statement, or ends the thread. (If there’s nothing more to run.)