closure in javascript working differently for me - javascript

Considering the following code snippet,
function outer(data1){
function inner(){
console.log(data1);
}
return inner;
}
in the following two function calls, first one works but not the second one.
var o = outer("sree");
o(); //works
outer("kumar"); //does not work
Please help me to understand better. Thanks.

Call like this:
outer("kumar")();
outer("kumar"); calling this will only get the reference of the inner function. By placing braces again it will call the inner function as well.

You're inner function has no parameters, you need to add one like this:
function outer(){
function inner(data1){
console.log(data1);
}
return inner;
}
You're code will always log in the console the parameter with which you created the object.

When you invoke the function outer("kumar") the function return a function, but that function is not invoked, that's the reason why this call do not log in console.
In the other hand, if you create a new variable invoking the function var o = outer("sree");, as I mentioned, the function outer return a function inner, then you invoke that function with the new variable created o();.

function outer(data1){
return (function inner(){
return data1;
});
}
The function outer returns another function 'inner', this is kind of a reference and to execute a function we need to call just like we called outer.
var o = outer("sree");
console.log(o());
The variable o contains ref to the function inner. to execute it we need to call (o()).
In your last action (console.log(outer("kumar"))), you have invoked first function and it resulted ref to 'inner' function, to get the output you have to invoke the second as well. The kumar will get printed as because the 'inner' method is with in the scope of the outer function.

Related

Why function returns unexecuted

If I write this code:
var foo = function (){
var x = 5;
return (function (){ return x;})();
}
alert(foo());
it alerts 5, as intended. But, if I do not use IIFE:
var foo = function (){
var x = 5;
return function (){ return x;};
}
alert(foo());
it alerts
function(){return x;}
I understand that in the first example IIFE runs and whatever it computes gets returned.BUT, if not using IIFE function returns without being executed.
Why is function returned before it is executed?
Functions in JS are first class objects. You can treat them in the same way as you can treat any object, including pass them about between functions.
If you don't do something to call a function, then it doesn't get called.
So is function(){return x:} which gets alerted in the second option a string
It is a function.
Functions, like any object, have a toString method.
alert() expects to be passed a string. Since you pass it an object, it will get converted to a string, which is done by calling toString().
Basically you are not executing the function before returning anything in the second example. You are just returning a function definiton with this row: return function (){ return x;};. This is why the function returns just the function that you placed after the return.
Functions are never called automatically. They can be passed as arguments, returned as values, assigned to variables, etc. and this just moves around references to the function. In order to call a function, you have to use the () operator.
Your first example does this by calling the function in the IIFE. "II" stands for "Immediately Invoked", and refers to putting () right after the anonymous function expression, so that you define it and then immediately invoke it.
In your second example, you simply return the function, and then pass it as an argument to alert(). alert() has no reason to call the function (it's not like map() or forEach(), which take a callback argument and are specified to call the function). If you want to execute the function, you need to call it explicitly, e.g.
var foo = function() {
var x = 5;
return function() {
return x;
};
}
alert(foo()());
The double () means to first call foo, then call whatever it returns, and finally pass the result to alert.

javascript function behaving differently

I have a function in javascript:
var a=function greet(){
console.log("Hello");
}
var b=a;
b();
While creating a new var b and assigning function a to b logs hello.However the code:
function greet(){
console.log("Hello");
}()
logs error.Why?
Also
(function greet(){
console.log("Hello");
})()
and
var a=function greet(){
console.log("Hello");
}()
logs "Hello".please explain the logic behind this.
function greet(){
console.log("Hello");
}()
There showing error because you invoked function immediately but not wrapped function body with '()'. So the invoke function immediately you should follow following pattern:
(fucntion(){ /* code*/ })()
But your first example is working because of you storing function in a variable and calling it later as a callback style.
As commented before, when you define a function expression, the function on RHS is treated as anonymous function. Reference of this function will not be registered.
Sample:
var a = function test(){
console.log("test");
}
test();
But when you declare a named function, it will be registered in heap and will retrieve its reference from there.
Now question is when is this action performed?
When ever its surrounding script is executed. i.e.
function test(){
// some code
} // when this line is evaluated, function reference will be added in heap.
But when you do
function test(){
console.log('test')
}()
when it reaches last line (}()), it will try to execute test(), but reference to this test is not defined yet and will throw error.
You may also ask why IIFE ((function (){...})()) works, thats is because, its surrounded by (). This makes it expression and outside this parenthesis, it becomes anonymous.
Note: As I'm not sure, making this as a community answer. Please add if anything is incorrect or missing.
As pointed out by #nnnnnn, my assumptions are incorrect. Please refer comments for more information.
In your first example you are assigning a function to variable a, then making b a reference to variable a. Then you are calling b which executes function a.
In your second example, you are creating a function, but you are not assigning it or calling it. If you simply call the function in your second example it will work as intended.
function greet(){
console.log("Hello");
}
greet();
Your third example is what is known as a 'self executing function' - meaning you don't have to call it for it to execute.
In your fourth example, you are assigning a function to variable a, but not executing it. The following adjustment will make example 4 work.
var a=function greet(){
console.log("Hello");
}
a();

JavaScript Closure: Returning a Function

I am working my way through a JavaScript lecture series by Douglas Crockford. I am confused by a code example he is showing to illustrate 'closure':
var digit_name = (function () {
var names = ['zero', 'one', 'two', 'three'];
return function (n) {
return names[n];
};
}());
alert(digit_name(3));
How/why can digit_name take an argument when no parameter is specified in the definition (the outermost function)? How does the argument (in this case 3) know to correspond to n within the inner function definition during invocation?
The digit_name stores the inner function returned by the outer function, which is an Immediately Executed Function Expression, where the inner function has the signature with one parameter and that's what is stored in the digit_name.
function (n) {
return names[n];
}
Ultimately, the above will be the digit_name and the names is a private variable, which is bundled with the environment of digit_name. The concept of private variable is possible only using closures.
To make it clear, see this:
Theres a self calling, anonymous function (function(){})() . So digit_name is not the function, its what the function outputs in is return statement.So this happens inside the browser:
var digit_name=(function(){})();
var digit_name=function(n){}
The outer function is an IIFE, an immediately-invoked function expression. That function is ran when the script starts and therefore the inner function returned by the IIFE is what is assigned to digit_name.
The "magic" of the closure if that this inner function still has access to everything in the closure (such as the names array).
https://developer.mozilla.org/en-US/docs/Glossary/IIFE

why does a variable need to be created in this closure

Hi I have the following closure
function createCounter() {
var numberOfCalls = 0;
return function() {
return ++numberOfCalls;
}
}
var fn = createCounter();
fn()
fn()
And I believe I understand about scope and the fact that the inner function keep the outer function's values after the outer one has returned.
What I don't understand is why I need to create this variable
var fn = createCounter()
and then invoke the variable fn() instead of initially invoking createCounter()
I saw that createCounter() just returns 'function()' instead of what has to be '1' and I don't understand why.
Thanks for the help. Read many tutorials still having problems with understanding this.
Please note: the question's isn't about how to make the code more eloquent or better, it's about understanding of what's been done
When createCounter is called it returns another function and that returned function is not evaluated unless you do so. Remember, in JavaScript functions are objects too. They can be the return value of a function.
So when you do this:
var fn = createCounter();
fn references only the function returned by createCounterfunction and not its evaluated value.
If you need to evaluate the function returned by createCounter try something like:
createCounter()();
This evaluates the returned function.
If you call it like this it will always return the same value as it creates a new numberOfCalls variable every time you call createCounter.
In Javascript, functions are objects which can be passed to and returned by other functions, as any other objects (e.g. a string, a number...).
So doing:
function foo(arg) { /* ... */ }
var someObject = new String("Hello");
foo(someObject);
is similar as:
function foo(arg) { /* ... */ }
var someFunction = new Function("Hello", "...");
foo(someFunction);
A function may thus return another function, which can be invoked as needed.
function foo() {
return new Function(...);
}
var functionReturnedByCallingFoo = foo();
functionReturnedByCallingFoo(); // can be invoked
functionReturnedByCallingFoo(); // and again
functionReturnedByCallingFoo(); // and again
Now, functions are almost never declared using the Function constructor, but rather with constructs named "function declarations" or "function expressions" - basically, the way we have defined the function "foo" in the previous examples, with a function signature and a function body delimited by curly brackets.
In such cases, the statements inside of the function body can read and write variables declared outside of the function itself ("free variables"), and not only variables declared within the function, as per the rules of lexical scoping. This is what we call a closure.
So in your case, the createCounter() function, when invoked, defines a local variable named "numberOfCalls", then return a function - the body of which having access to that variable. Executing the returned function changes the value of the variable, at each invocation, as it would for any "global" variable (i.e. variables declared in outer scopes).
Executing the createCounter() function many times would simply, each time, recreate a new local variable "numberOfCalls", initialize it to zero, and return a new function object having access to that variable.

Confusion about variables equaling functions JavaScript

I have these functions:
function change(num1, num2){
//return number
}
function getFunction(funct){
//return function
}
this declaration:
var funct = getFunction(change);
and this call
funct(array);
I am confused about what the call does. Where does it send array, what exactly is it doing? I just can't wrap my head around it. When sending the function change() into getFunction() what exactly does this do and again how does JS handle funct(array)? Let me know if I need more info.
getFunction returns a function.
var funct = getFunction(change);
funct is now assigned to the returned function reference
funct(array) is just calling the function returned from the previous assignment.

Categories

Resources