JS functions as variables

if you saw a function like this, how would you retrieve the result of the add function?

f(3,5,5); : does this not call the function?

var f = function(x, y, z) {
  if(x==3){
    function add(y,z){      
      return y+z;
    }
  }
}; 
console.log(f(3,5,5));

the function add is not called anywhere, and f doesn’t return anything.
I don’t know what you want to do, but if you return the result of add from inside f then it works. Something like this:
this would return the result of add from inside f

var f = function(x, y, z) {
  if(x==3){
    return (function add(y,z){      
      return y+z;
    })(y, z);
  }
}; 
console.log(f(3,5,5));
1 Like

Thanks @ilenia
I’m doing the MongoDB and Mongoose lessons and I’m trying to understand callback functions.
Functions inside functions, closures, etc.

I’m experimenting by trying to write my own simplified versions.

what I used there is an IIFE, immediately invoked function expression, take a look at those too

1 Like