I’m new to programming and I don’t understand how and why return is used. Could you explain it to me? preferably with an example, I’m a bit dumb
Hey Dude,
Functions don’t need to return
anything unless you are chaining functions together.
This means that function A
relies on the value of function B
running and "returning"
a value …
This is usually so that you don’t have to write 1 big massive function for your entire program and also:
- Code readabilty
- Testing
- Re-use
- Control flow
- understandable logic
- So your head doesn’t explode…
Basically when you are chaining functions you’re:
- Running a function and saving it to a variable (temporary or permanent variable)
- Running another function with the result of the first function (saved in the variable)
- Repeat until you do something with the result
If you don’t return
a "value"
from any function in the “chain” what will happen is:
- the variable storing the function result will be
undefined
- the next function in the chain will try to run with
undefined
as its main argument - that function will probably throw an error
- you wont be able to continue with the chain and get a result
This chaining is also called piping.
Here’s a basic example of it with some simple addition.
(this will run in the browser console)
Try to wrap your head around the function stepper
at the start
let object = {
value1: undefined,
}
let add1 = function(x){
return x + 1;
}
let add2 = function(x){
return x + 2;
}
let add3 = function(x){
return x + 3
}
// does nothing returns x
let returnX = function(x){
return x
}
let noReturn = function(x){
object.value1 = x
}
// pipes a number through an array of functions
let pipe = function(number, array){
let accumulator = number;
for(let fn of array){
accumulator = fn(accumulator);
}
console.log(accumulator)
return accumulator
}
// does the same as pipe but its hard coded without an array of functions
let stepper = function(x){
let a = add1(x);
let b = add2(a);
let c = add3(b);
console.log(c)
return c
}
pipe(5, [add1,add2,add3]) // returns 11
pipe(5,[add1,add2, add3,returnX]) // returns 11
pipe(5, [add1,add2,add3,noReturn]) // returns undefined
stepper(5)// returns 11
1 Like