Use of () in javascript for a function - javascript

Sorry if its being a noob question, but I still can't understand the difference of its usage so I am unable to search on google with right keywords to search for.
I am following this tutorial on Closures.
Now my query is for this code -
function makeFunc() {
var name = "Mozilla";
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
Why displayName being a function is referenced as a property in the code ? Do being a closure function it needs to be returned as a property as I tried this code -
function makeFunc() {
var name = "Mozilla";
function displayName() {
alert(name);
}
return displayName();
}
var myFunc = makeFunc();
myFunc();
Output - An alert but an error TypeError: myFunc is not a function.
Let me know when to use what or what basic concept I am missing here.

"return displayName;" is returning the function displayName.
The result is then being set to myFunc.
function makeFunc() {
var name = "Mozilla";
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
It is easier to understand if you think of:
function displayName(){}
as an alternative to:
displayName = function(){}
makeFunc = function () {
var name = "Mozilla";
displayName = function () {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();

In first case, you're returning a function reference which you can use later. In the second case, you are returning the result of the function which is undefined since you're not returning anything. So the error comes up as myFunc is not a reference to a function and hence cannot be called.
Other than the above, I don't know what you're meaning to say when you say "property".

return displayName()
this code returning not the function, but result of calling this function.
var myFunc = makeFunc();
myFunc();
the same.in myFunc not the function, but it's result.
try to do this:
return displayName;
...
var myFunc = makeFunc(); //makeFunc() will return displayName() function
myFunc();

Before understanding closures, which is a concept extended from the Javascript function scope.
Closures: allows certain variables to get accessed within the scope being created.The inner function can get accessed to the outer function as well as its variables.But the outer function cannot access variables within the inner function.
So in your closure example, the reason why output alerts "Mozilla" is because your inner function-displayName alerts the name variable declared in the outer function (displayName can get access to any variables in the makeFunc function). So when your makeFunc function invokes the inner function-displayName, you will get a TypeError with undefined. Same result will output when you simply call the makeFunc(), you get undefined.

Related

I am having trouble returning a value (a function) [This question isnt a duplicate question] [duplicate]

This question already has answers here:
I don't understand function return in javascript
(3 answers)
Closed 3 years ago.
Why does the inner function run when I write return displayName; but it doesn't run when I write return displayName();
I usually call a function like this:
functionName();
so I am very confused.
Here are my functions:
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
VS
/*
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName();
}
var myFunc = makeFunc();
myFunc();
*/
When you do:
return displayName; // returns a function
You are returning a function which can, later on, be executed/called (as you are doing with the myFunc variable).
When you do:
return displayName(); // returns whatever the displayName function returns (undefined)
You are firstly calling the displayName() function, which in your case will evaluate to undefined as it does not return anything within it. So the above return statement is similar to:
return undefined;
Thus, as you are returning undefined, myFunc will be set equal to undefined, and so you cannot call it as a function (ie: undefined() will give you a TypeError)
So looking at your first example you can see it returns a function, which is later executed (read code comments for further explanation):
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName; // returns a function TO BE called LATER
}
var myFunc = makeFunc(); // makeFunc() "turns into" the returned (inner) function, so we have: var myFunc = displayName;
myFunc(); // call myFunc, like so myFunc(). As myFunc is equal to displayName, this is the same as doing displayName();
"The second one makes the code work how I want it to work? is this how youre supposed to return functions?"
Well yes and yes.
That pattern that you're applying is called function factory, that is a function that returns another function, that you later call.
When you type return displayName();, myFunc will return undefined and the value of the variable myFunc assigned to undefined because call to displayName actually return undefined or absolutely nothing(it just make a call to alert and then ends). So when try to call myFunc which is undefined it will give you a type error.
But when you return displayName;, the function makeFunc return a function and myFunc will assign to a proper function and just run fine.
I would say when you do return displayName(); you are returning the result of the function and then when you do myFunc(); you are treating that result as a function. In the current scenario, it is a undefined but it could also be a string or int. Contrary, when you do return displayName you are returning a function definition that can be invoked by doing myFunc().

What is the difference between displayName(); and return displayName;?

I am an aspiring front-end developer. I was reading an MDN article about closure in JavaScript. The MDN article used the following two code examples to explain the basic concept. Though I understood the basic concept, I have the following doubt.
What is the difference between displayName(); and return displayName ?
function init() {
var name = 'Mozilla'; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert(name); // use variable declared in the parent function
}
displayName();
}
init();
**
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
In the first case it is executing the function , while in second case makeFunc is returning another function.Check the console.log. That is the reason there is a () after myFunc() which will execute the function returned from makeFunc
function init() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
displayName();
}
init();
function makeFunc() {
var name = 'Mozilla';
function displayName() {
alert(name);
}
// this is returning a function
console.log(displayName)
return displayName;
}
var myFunc = makeFunc();
// since it is returning a function it is getting executed ony after adding () with it
myFunc();
What's the difference between displayName() and return displayName?
The difference is that the first is invoking the function displayName while the second is returning it. To see an example of what that means:
const log = () => console.log('I was invoked!')
const getLog = () => {
return log
}
const doLog = () => {
log()
}
We have some function that, when invoked, prints to the console. We also have two other functions, one that returns log and one that invokes it. When we call getLog(), we don't see anything printed to the console. When we call doLog(), we do.
Another point is that getLog returns the value of log. So we can do this as well:
const logByDifferentName = getLog()
which wouldn't cause log to be invoked but assign it to another value.

not able to execute the named functions that are also refereed

i'm learning about functions. i'm confused in one scenario.
suppose i have three functions
<script>
var fnRef = function() {
console.log("i'm function with no name but refered to fnRef");
};
var funRef2 = function test() {
console.log("im test reffered to funRef2");
};
function test2() {
console.log("i'm test2 named function")
};
</script>
fnRef, fnref2 and test2 will be assigned to window as a property as fnRef and fnRef2 are variable and test2 is named function that act as variable.
but why test2 is not assigned to the global object(window) when refered by funref2? and why i'm not able to execute test(); can someone tell me what is happening in detail.
The named function expression is useful so you can access the function inside it's own scope without using arguments.callee, and it also makes it easier when debugging as the name can be seen in stack traces, breakpoints etc.
This name is then local only to the function bodys scope, meaning
var test1 = function test2() {
if (something) test2(); // available in this scope only
}
test2(); // not here
You can't call the function by it's name, only by the variable it's assigned to, as the functions name is limited to the functions scope when it's a function expression.
When defining a function declaration, the name is assigned to the current scope, and hoisted, so this
var bar = test();
function test() { return 'foo'; }
is more or less turned into this
var test = function() { return 'foo'; }
var bar = test();

Why is the function returned from a callback function not forming closure over the function where it is called?

I am having trouble in understanding the output from the below code (In Javascript) :
function outerFunction(callback){
var x =10;
var myCallbackRet = callback();
myCallbackRet();
}
outerFunction(function(){
return function(){
console.log(x); //output - x is not defined
}
});
As far as i understand when function myCallbackRet is called then [[Scope]] property of myCallbackRet is set to the Scope chain of the outerFunction and so the variable x should be accessible inside `myCallbackRet'.
Why is the output 'undefined'? Thanks a lot in advance.
Basically it has to do with where your function is defined. It was defined out of scope. Closure only works when a function is defined some where. Setting a variable to a function and calling it doesn't make everything above it available inside the function being called or there would be no reason to pass parameters to a function. Something like this would work.
function outerFunction(callback){
var x =10;
var myCallbackRet = callback();
myCallbackRet(x);
}
outerFunction(function(){
return function(y){
console.log(y);
}
});
Or this:
function outerFunction(callback){
var myCallbackRet = callback();
myCallbackRet();
}
outerFunction(function(){
var x =10;
return function(){
console.log(x);
}
});
Your anonymous function
function(){
return function(){
console.log(x)
is defined on the same scope (global) as outerFunction, but x is defined inside the scope outerFunction.
The scope of the function is set at the moment the function is defined, rather than at the moment when a function is assigned to variable.

Does a Javascript self executing function work like a compiled program

Does a Javascript self executing function work like a compiled program. I.e can you declare some function after a named anonymous function within a self executing function and have the named anonymous function locate the other function at runtime? I.e why does the following work?
I'd thought that you could not hoist named anonymous functions as they are only created during runtime so perhaps the self executing function "compiles" the code to make the named anonymous function available to the function that calls it!!
(function(){
var myFunc = function(){
var bar = "Bar";
return myFunc2() + bar;
}
function myFunc2(){
return "Foo ";
}
})()
or even
(function(){
function myFunc(){
var bar = "Bar";
return myFunc2() + bar;
}
var myFunc2 = function(){
return "Foo ";
}
window.fooBar = myFunc();
})()
console.log(fooBar);
That particular example works because myFunc2 is never called because myFunc is never called.
In general though, the normal rules for JS scope, hoisting and timing apply:
A variable must be populated before you use it, not before you define a function that will use it when called.
Lets see what actually happens in your code.
1.you have a function that performs a variable assignment:
var myFunc = ;
2.you declare a function. (But don't yet invoke it)
3.you assign myFunc to window.foobar.
4.And you invoke the function you were defining.
Now, these steps happen:
myFunc gets a function as its value.
myFunc2 gets defined.
window.foobar gets the result of calling myFunc().
so what happens is, myFunc() returns the result of invoking myFunc2() and appends its result to bar.
Thus, the value of window.foobar will be "foobar".
(no, this is not how compiled programs work)
(function(){
var myFunc = function(){
var bar = "Bar";
return myFunc2() + bar;
}
function myFunc2(){
return "Foo ";
}
})()
After some hoisting this becames:
(function(){
var myFunc;
function myFunc2(){
return myFunc2() + bar;
}
myFunc = function(){
var bar = "Bar";
return "Foo ";
}
})()
And actually this will work if you call myFunc(); and log the returned value from myFunc2 you will get Foo Bar.
When hoisting named anonymous functions(which is actually function expression), only
var myFunc (= undefined); is hoisted. Then the assignment stay at the same level.
Also you cant refer this function as self execution function(because self executed function is actually recursion). This is Immediately Invoked Function Expressions.
And #Quentin said the rest: A variable must be populated before you use it, not before you define a function that will use it when called.

Categories