[Beginner Question] Is using Anonymous Functions basically a preference?

As the title says. I feel like so far as I have coded, anonymous functions just seem like a preference of choice in programming. But as well knowing that named functions are as much useful due to the recallability of them later in a script. I would like to hear your thoughts or feedback on this topic.

I’ve never thought about it, but from my experience, there isn’t a place where functions must have a named function declaration or be anonymous, so I suppose it’s down to preference.

As you said, named functions are better than anonymous ones when the function’s code is frequently used. Moreover, well-named functions can say a lot about what a function does, and they can make code “neater” in some cases.

For example (as one among many), the following code…

-- some background...
-- * ContextActionService (CAS) is a useful service which allows
--   actions to be bound to key presses or other input types
-- * e.g. a gun can be fired when the mouse is clicked

-- why this is relevant to anonymous functions...
-- * the BindAction() method takes a few arguments, including a function,
--   which can be either named or anonymous (here it's anonymous)
-- * actionName, inputState, and inputObject are arguments which
--   are passed through the anonymous (or named) function 


local CAS = game:GetService("ContextActionService")

CAS:BindAction(
    "OnGunUse", 
    function(actionName, inputState, inputObject)
        -- do something
    end, 
    false, 
    Enum.UserInputType.MouseButton1
)

… would be more readable as (and this is what I prefer)…

local CAS = game:GetService("ContextActionService")

local function fireGun(actionName, inputState, inputObject)
    -- do something
end

CAS:BindAction("OnGunUse", fireGun, false, Enum.UserInputType.MouseButton1)

-- * the function has a name now, so it's purpose is clearer (although
--   arguably the action name "OnGunUse" make it fairly clear)
-- * it's also separated from the bind method, making the action distinct 
--   and the code a bit easier to read

It’s just a matter of preference and style IMO. :wink:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.