1

See this:

var funkyFunction = function() {
      return function() {
        return "FUNKY!"
      }
   }

var theFunk = funkyFunction(funkyFunction())

I need theFunk variable to be assigned value "FUNKY!" from the inner function but I have no idea how to go about it?

Shahid Manzoor Bhat
  • 1,307
  • 1
  • 13
  • 32
  • 2
    `var theFunk = funkyFunction()();` – ASDFGerte Dec 10 '19 at 16:25
  • Right now you're passing in the result of calling `funkyFunction` into `funkyFunction`, which takes no parameters. Think about it: You're calling a function that returns a function: `const aFunc = funkyFunction()`. How do you call a function? By tacking on `()` at the end: `aFunc()`. Done. And you can combine it into a single call; `funkyFunction()()`. – Dave Newton Dec 10 '19 at 16:25
  • 1
    take reference from the previously asked question: https://stackoverflow.com/questions/7629891/functions-that-return-a-function – Sarvesh Mahajan Dec 10 '19 at 16:28
  • Does this answer your question? [Functions that return a function](https://stackoverflow.com/questions/7629891/functions-that-return-a-function) – whoami - fakeFaceTrueSoul Dec 10 '19 at 16:35

2 Answers2

3

Since funkyFunction is returning a function, the result of invoking funkyFunction can then be invoked:

var func = funkyFunction();    // 'func' is the inner function
var theFunk = func();    // 'theFunc' = 'FUNKY!'
Matt U
  • 4,970
  • 9
  • 28
  • 1
    thank you so much that worked, why is that we have to include one extra step to access the inner function? – Dinno Roni S Dec 10 '19 at 16:31
  • 1
    @DinnoRoniS because `funkyFunction` is returning a function. You can do this inline as well `funkyFunction()()`. Since `funkyFunction()` returns a function, the extra `()` at the end will invoke the function that is returned. – Matt U Dec 10 '19 at 16:32
  • @DinnoRoniS Same reason I put in my comment. A function is just another value, and to call it, you need the `()`. You're calling a function (with `()`) that returns a function, to call it you need the `()` as with any other function. – Dave Newton Dec 10 '19 at 16:35
0

With ES6/ES7 You can return a function from within a function without naming the inner function.

const myOuterFunction = () => {
  // the ...args just places all arguments into an array called args (can be named whatever)
  console.log("OuterGuy");
  return (...args) => {
    //Whatever Else you want the inner function to do
    console.log(args[0]);
  };

};

//The way you call this

const innerGuy = myOuterFunction();
const randomVariableThatINeed = 'Yay!';
//Call inner guy
innerGuy(randomVariableThatINeed);
Toni
  • 5
  • 5