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!
}
foo();
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?
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.
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()