Closures
In this code snippet, which function is considered a closure? var seenYet = function() { var archive = {}; return function(val) { if (archive[val]) { return true; } archive[val] = true; return false; } }
The anonymous function returned by the function named 'seenYet'
Which of the follow functions - multiplyByX and multiplyByFive - demonstrate the use of closure? var multiplyByX = function(x) { return function(y) { return x * y; } } var multiplyBy5 = multiplyByX(5); multiplyBy5(4); var multiplyByFive = function() { return function(y) { return 5 * y; } } var multiplyBy5 = multiplyByFive(); multiplyBy5(4);
multiplyByX uses closure because the returned function still has access to the value x.
After running the following code, what is the value of total? var add = function(x) { var sum = function(y) { return x + y; } return sum; } var foo = add(1); foo(3); var total = foo(6);
7
How do you define closure in javascript?
A closure is a function object which retains ongoing access to the variables of the context it was created in - even after the outer function calls it was created in have returned.
What is a closure?
A closure is an inner function that has access to the outer (enclosing) function's variables- scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function's variables, and it has access to the global variables.
