1

I am trying to understand the flow of the following code snippet -

var inner = function (a){
    console.log("a is -- ", 9);
}

var outer = function(b){
    console.log("Executing outer()");
    b();
}

outer(inner(5));

The output currently is -

a is --  9
Executing outer()
app.js:6 Uncaught TypeError: b is not a function 
at outer (app.js:6)
at app.js:9

I am expecting the following -

Executing outer()
a is --  9

I understand that in the statement outer(inner(9)) : inner(9) is a function call that evaluates (runs the code contained within the inner() function), but i want the code inside the outer() function to evaluate the code within inner(). Basically, i want to pass 9 as a variable to outer() so that it can pass it to inner()

Please point me to any online resource that will help me understand this concept better. Also, please mark this question as duplicate if already answered. Thanks!

tprk09
  • 103
  • 1
  • 7

3 Answers3

2

The call within outer is made without passing any arguments to the callback function b:

b();

So as you say, you need to pass in as b a function that, when called without arguments, effectively makes the call inner(5) and returns its value.

However compelling the visual similarity of such a b with the expression inner(5), the result of the latter is something else: it is not "a function that, when called...", but rather the return value of inner: undefined.

What you need can be achieved either as a classic Javascript closure:

outer(function() { inner(5); }); // return omitted as value uninteresting

or using Function.prototype.bind:

outer(inner.bind(this, 5));

or using a more modern ES6 arrow function:

outer(() => inner(5))
Jon
  • 428,835
  • 81
  • 738
  • 806
0

Can return a function from inner and all the rest stays the same

var inner = function(a) {
  return function() {
    console.log("a is -- ", a);
  }
}

var outer = function(b) {
  console.log("Executing outer()");
  b();
}

outer(inner(5));
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • doesn't the **inner** variable itself represent the function() ? How do i make the outer() evaluate the inner() ?? – tprk09 Jul 07 '17 at 21:49
  • Not when you call `b()` because inner didn't return anything and that's why you get `b is not a function` after you invoked `inner(5)` – charlietfl Jul 07 '17 at 21:50
0

What your looking for would work in a sample like this:

var inner = function(a) {
  return function() {
    console.log("a is -- ", a);
  }
}

var outer = function(b) {
  console.log("Executing outer()");
  b();
}

outer(inner(9));

Though you might want to look at Javascript Promises for something like this.

https://developers.google.com/web/fundamentals/getting-started/primers/promises

This way, you can chain together functions to do something like:

outer(9).then(inner())

You can have the function outer return something that then gets passed into inner.

Rolando
  • 58,640
  • 98
  • 266
  • 407