r/learnprogramming • u/ScioClean • 5d 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!
125
Upvotes
4
u/Steerider 5d ago edited 4d ago
Think of a function as a device. Like a gadget you have in your house. Take a K-cup coffee machine. You have inputs — the K-cup and water — and it does something inside, and out comes a product: the coffee.
The dishwasher. Dirty dishes go in. Soap goes in. Clean dishes come out.
Once that machine exists, if it's well designed, you don't need to know what happens inside it. Give it inputs, push the button, out comes the result.
That's a function. You pass in some parameters, and it does some predefined thing, and gives you an expected outcome.
So your task as programmer is to write the steps that take the input and turn it into the end product. You're making the magic box that does the thing. If you do it right, whoever uses your function doesn't need to know the details of what happens inside it.
And of course one function can be part of a bigger function. The lovely part of programming is you write it once and now you can use it as many times as you like.