jsc42
jsc42

Reputation: 117

Return value from nested function in JS

Super beginner here, I read the similar questions asked here and it did not solve my problem.

I know the instructions say that I'm only supposed to amend the final line (var burger...), but I cannot get this one to pass.

var food = function() {
  return function() {
    return "HAMBURGER"
  }
}

var burger = food();

I want to return "HAMBURGER" but instead I return [Function]

Upvotes: 3

Views: 2540

Answers (3)

Tigerrrrr
Tigerrrrr

Reputation: 1344

The same solution but with better code.

  1. If you are going to have a nameless function, I'd suggest using an arrow function.
  2. var food = function() { ... is identical to function food() { ...
  3. "Self-invoke a function" using (<Function>)().

Here's your new code:

function food() {
  return (() => {
    return "HAMBURGER"
  })();
}

food(); // "HAMBURGER"

Instead of return a regular function, we return and immediately

Upvotes: 0

MaxZoom
MaxZoom

Reputation: 7743

As the function food returns an anonymous function, it has to be invoke to run and produce some result:

var food = function() {
  return function() {
    return "HAMBURGER"
  }
}

var burger = food()(); // or food().call()
console.log(burger)

An interesting article about different ways of function invocation could be found here.

Upvotes: 3

Robbie
Robbie

Reputation: 19500

The simplest thing you can do if you are only supposed to change the bottom line is to change it to:

var burger = food()();

Which is the equivalent of:

var burgerFunction = food();
var burger = burgerFunction();

Your function returns a function, so you need to invoke them both

Upvotes: 3

Related Questions