Function returning a function - example from reading material

Hi all,

Struggling with a concept or at least the example below from “https://www.tutorialsteacher.com/javascript/javascript-function” which was 1 of the reading assignments on the course.

I am struggling to understand the flow of parameters…I mean I get for example where it states…document.getElementById(“p1”).innerHTML = triple(2);

From “var triple = multiple(3);” I guess we are setting x=3, but where or how are we defining what “y” needs to be?

The result of “triple(2)” is 6, and I can guess how it comes to this, but its really bugging me I can seem to logical follow the numbers through.

Any help much appreciated.

Jason

Demo: Function returing a function

  <script>

  function multiple(x) {

		function fn(y)
		{
			return x * y;
		}

		return fn;
	}

	var triple = multiple(3);


  document.getElementById("p1").innerHTML = triple(2);
	document.getElementById("p2").innerHTML = triple(30);


  </script>


  </body>

Hey Jason,

This is how I try to visualize it:

document.getElementById(“p1”).innerHTML = triple(2);

Does:

triple(2) = multiple(3)

This executes the function multiple(3), returning the function fn, a function can be executed without parameters. So the return of the function fn is now “3 * undefined”
In code this means:

var triple(2) = function fn(y)
{
return 3 * undefined;
}

So now the parameter “y” will be filled with the number 2. Making that the equation will be solved setting the value of 6 to element with id p1.

By calling “triple(2)” you are executing "Multiple(3). Multiple returns the function fn(y). So you are entering 2 as Y. X is filled in the first call as 3, Y is filled in in the return as 2. Eventually returning 3 * 2.

I hope this insight helped and is not to confusing. And if anyone else has anything to add, feel free.

1 Like

Jordi, seriously appreciate you taking the time to explain that to me.

Definitely makes more sense now.

Thanks you!

1 Like

Glad I could help. :slight_smile: