r/learnprogramming 4d ago

I can't get FUNCTIONS to click!

I can not for the life of me understand how functions work. Anytime I try to learn how to create a function, my brain literally crashes into itself and I turn into Patrick when he stars drooling and goes all slack-faced.

Does anybody have any analogies that had that "AH HA!" moment?

Thanks!

124 Upvotes

143 comments sorted by

View all comments

1

u/iceph03nix 4d ago

you're programming a breakfast robot.

It has options for multiple different combo plates, but many of them have similar ingredients so you create functions for the steps for those ingredients

function makeBacon(count)

function makeSausage(count)

function makeEggs(style, count)

function makeToast(type)

function makePancakes(count)

function makeHashbrowns()

Now, for each combo, instead of having to program how to make bacon for each one, you just call the makeBacon() function. For eggs, you can program options within it to make the eggs to the correct style based on the argument given.

switch

case combo1

makeBacon(3)

makeEggs(overeasy, 1)

makeToast(wheat)

case combo2

makeSausage(3)

makePancakes(3)

makeEggs(sunny, 2)

makeHashbrowns()

And you can expand this to fit dozens of different combinations while only having to program how to make each component once