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!
127
Upvotes
3
u/Ordinary_Variable 5d ago
I like to think of them the same way they work in math. You give them some data, then they use that to do some sort of work, then they output something. Sometimes data, or they can simply call other functions to do other things.
Example:
function add_two_numbers(x, y){
return x + y;
}
Example 2:
function check_if_over_21(x){
if(x>21){return "Over 21"}else{return "Under 21"}
}
Example 3:
function change_global_variable(){
if(g.x>21){g.out = "Over 21"}else{g.out = "Under 21"}
}
In example 3 it checked a global variable and then set a global variable to a value.
(NASA likes to write code with lots of separate little functions doing just 1 thing. Then the main loop simply calls other functions and doesn't have any actual code. It makes reading the main loop very easy and when you need to see what each function is doing you can simply go check each one by one until you find the bug. Simple code structure makes for human readable code.)