Assign variable to function VS assign function to variable

Assign variable to function VS assign function to variable

var fn;

function foo() {
	var a = 2;

	function baz() {
		console.log( a );

	fn = baz; // assign `baz` to global variable

function bar() {
	fn(); // look ma, I saw closure!


bar(); // 2

I know that in the code above, we passed a function to a variable. fn=baz, if I change it to fn=baz() IDE will give me a type error: fn is not a function. So I assume in js we do not assign functions to variables, we assign the output of the functions into a variable. Because the elements at the each side of = has to be the same type. Am I correct?

Then what does this mean? function bar(){fn();}? why do we need to add a parameter after a variable?

I am a bit confused…


You can assign functions to variables (because in JS you can pass around functions as if they were plain data), like in var f = function() {...};. You can also invoke the function in f by writing f() in your code.

Also, variables in JS have no type. A variable that previously held a number doesn’t care if you assign it a string or array, or a function

When you changed it to fn = baz(), you were invoking the baz function, which returns undefined (simply because there are no return statements in that function). So fn now is undefined, which is definitely not a function, and you get the error when fn() was executed.


I don’t think that baz function returns undefined because here in this example, it returns 2.

function baz(){
	var a=2;

var fn=baz();


But to understand the code I put 1st was

  1. baz got assigned to fn 1st via fn=baz.
  2. then baz got invoked via function bar(){fn();}.


Don’t confuse the result of console.logging with return values. The 2 that you see is not a return value, but rather the result of console.logging the 2 from inside baz(). When a function has no return statements, their return values are implicitly undefined.

True. The global fn variable holds a reference to the baz function. Then you can later invoke the baz function by using fn()


I will remember this from now on. Thanks!!