How are arguments from wrapper functions passed on to functions after the keyword 'return'?
function greeting(name){
console.log("Hello, " + name)
}
function wrapper(f){
return function(args){
if(typeof(f)==='function'){
console.log("before executing wrapped")
f(args)
console.log("after executing wrapped")
}
else{
return f
}
}
}
let a = wrapper(greeting)
a("Maria")
So, this works fine, and prints the intended
before executing wrapped
Hello, Maria
after executing wrapped
because arguments from f
are passed on to the line return function(args){
. However, had I not the return
keyword there, the arguments from f
wouldn't have been passed on to the anonymous function. How/why does this happen?
Example of a non-working-version of similar code (only changes to the wrapper function):
function greeting(name){
console.log("Hello, " + name)
}
function wrapper(f){
if(typeof(f)==='function'){
function a (args){
console.log("before executing wrapped")
f(args)
console.log("after executing wrapped")
}
return a(args)
}
else{
return f
}
}
let a = wrapper(greeting)
a('Maria')
Of course, this returns ReferenceError: args is not defined
.
I'm curious to know what's up with the return
keyword that makes the first piece of code work.