Recent Posts

Showing posts with label closure. Show all posts
Showing posts with label closure. Show all posts

JavaScript closure inside loop example

When we want to bind a variable within an anonymous function unchanging value outside of the function, you can implement the following javascript code: var funcs = []; function createfunc(i) { return function() { console.log("My value: " + i); }; } for (var i = 0; i < 3; i++) { funcs[i] = createfunc(i); } for (var j = 0; j < 3; j++) { funcs[j](); // and now let's run each one to see } Since...

How does JavaScript closure works

Whenever you see the function keyword within another function, the inner function has access to variables in the outer function. function foo(x) { var tmp = 3; function bar(y) { alert(x + y + (++tmp)); // will alert 16 } bar(10); } foo(2); This will always alert 16, because bar can access the x which was defined as an argument to foo, and it can also access tmp from foo. That...