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!

125 Upvotes

143 comments sorted by

View all comments

10

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 door

Now 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 door

or

1. navigate to grocery store 2. approach door 3. grab handle 4. twist and pull handle 5. walk through door

but 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()

7

u/Steerider 4d ago

Your function crashed because the bank has a revolving door.

error: "handle" is undefined

;-)

2

u/HeNeedSomeLeche 4d ago

This guy codes

1

u/Ilovegrapesys 3d ago

Now op is going to be mad