The closure code is very short:
var fn = function() { return function() { console.log(arguments); } } (function(arg) { console.log('bar'); })('foo');
Why ["foo"]
is printed instead of bar
? If I comment out var fn = ...
, the result is as expected and bar
is printed. How can those 2 pieces of code be related?
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
Closures are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.
3How would you use a closure to create a private counter? You can create a function within an outer function (a closure) that allows you to update a private variable but the variable wouldn't be accessible from outside the function without the use of a helper function.
Closures are useful because they let you 'remember' data and then let you operate on that data through returned functions. This allows javascript to emulate private methods that are found in other programming languages. Private methods are useful for restricting access to code as well as managing your global namespace.
Without the semicolon after the }
of the fn
, you are actually calling the fn
with argument (function...)
.
If you add the missing semicolon, it works as you expect:
var fn = function () { return function () { console.log(arguments); } }; (function (arg) { console.log('bar'); })('foo');
Why
["foo"]
is printed instead of'bar'
? How can those 2 pieces of code be related?
With the parenthesis around the (function(arg) {…})
it is considered as a function expression's argument, just as you expected ('foo')
to be the argument of the IEFE. Actually, foo
is now passed to the function that is the result of the first invocation:
var fn = ( (function() { return function() { console.log(arguments); }; }) (function(arg) { console.log('bar'); }) ) ('foo');
To fix this, either always put a semicolon after your assignments, or use a function declaration:
function fn() { return function() { console.log(arguments); } } (function(arg) { console.log('bar'); })('foo');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With