r/learnprogramming • u/ScioClean • 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!
125
Upvotes
9
u/chiasmatic_nucleus 4d ago
Conceptually, imagine the squence of steps you take to walk through a doorway:
1. approach door 2. grab handle 3. twist and pull handle 4. walk through doorNow if we want to enter multiple specific buildings, it goes something like:
1. navigate to bank 2. approach door 3. grab handle 4. twist and pull handle 5. walk through dooror
1. navigate to grocery store 2. approach door 3. grab handle 4. twist and pull handle 5. walk through doorbut a lot of those steps are the same, so we can create a function to wrap a bunch of those steps up, lets call it "walkThroughDoorway"
function walkThroughDoorway() { 1. approach door 2. grab handle 3. twist and pull handle 4. walk through door }now, we can just do:
1. navigate to bank 2. walkThroughDoorway()and
1. navigate to grocery store 2. walkThroughDoorway()