Is my understanding correct when returning functions

Hi guys, can you enlighten me as to wht is happening here, is my thinking correct:

function foo() {
	var a = 2;

	function bar() {
		console.log( a );
	}

	return bar;
}

var baz = foo();

baz(); // 2

When foo(); is assigned to var baz (var baz = foo(); ) foo(); runs and assigns function bar(); to baz(); so running baz(); is as if we are running bar(); outside of the scope it was declared in, but because of closure function bar(); which is now theoretically baz(); has closure over the scope of foo(); so it can access the “var a” variable.

Is this correct?

So if we did this:

function foo() {
	var a = 2;

	function bar(x) {
		console.log( a + x );
	}

	return bar;
}

var baz = foo();

baz(3); // 5

in this example is it correct to assume after foo(); is assigned to var baz, baz(3); becomes equivilent to running bar(3); from outside the scope it was declared in.

I understand that you can ot run bar(); outside of the function it was declared in so I am assuming the only way to achieve this is to assign foo(); to var baz (var baz = foo(); ).

Yeah, you’ve got it.

Yup. This is an important pattern in JavaScript. You can find great examples of it in Mike Bostock’s D3 examples, in particular his reusable charts.

Awesome, thanks for confirming this puts my mind at ease I can move onto something new now because this hs been bugging me forna week! :joy:

I’ve been given a few explenations and they did not seem right so i kept looking into it myself and this was the only one that actually made sence! :slight_smile: