Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript closure unexpected result

Tags:

javascript

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?

like image 829
MichaelYu Avatar asked Apr 09 '14 10:04

MichaelYu


People also ask

What is Clouser in JavaScript?

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.

What are closures few common uses for closures?

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.

How would you use a closure to create a private counter?

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.

Why are closures useful?

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.


2 Answers

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'); 
like image 133
dkasipovic Avatar answered Oct 02 '22 15:10

dkasipovic


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'); 
like image 23
Bergi Avatar answered Oct 02 '22 16:10

Bergi