Difference between passing a callback versus a function - javascript

I'm curious, is there any difference between the two functions below?
Is one just passing a function inside an anonymous function when ready whereas the other is passing an actual named function when ready?
Example:
<p>Not loaded yet.</p>
First method:
function newName() {
$( "p" ).text("The DOM is now loaded and can be manipulated.")
}
$(document).ready(function() {
newName()
});
Second method:
function newName() {
$( "p" ).text( "The DOM is now loaded and can be manipulated.")
}
$(document).ready(newName());
Is one more correct than the other?

Is one just passing a function inside an anonymous function when ready whereas the other is passing an actual named function when ready?
Yes and no.
I'm curious, is there any difference between the two?
The first is passing an callback function that is executed when the event fires. When that even fires is explained here.
The latter passes the resolved return value (which is undefined because newName has no return statement), which isn't the same as the second. The reason it passes the return value to ready is because you invoke the function immediately (which may seem like it works), which then passes the return value. To make them functionally equivalent, do:
$(document).ready(newName);
This will pass a function reference, and won't invoke it. Also, as mentioned before, invoking as ready(func(); func2();) is not valid syntax.

Effectively there’s no difference between
$(document).ready(function(){
newName();
});
and
$(document).ready(newName);
There’s a small technical difference: in the first snippet, an anonymous function calling newName is passed, in the second snippet, the named function newName itself is passed.
Functions are just callable objects that can be referenced by their name or the name of a variable holding the function.
Note that $(document).ready(newName()); is calling newName — immediately — and passing the return value to ready. This only makes sense if newName returns another function, which in this case it doesn’t.
The title also mentions something like $(document).ready(newName){}. I’m assuming that’s a typo, since that’s not valid syntax.
$(document).ready(newName(); otherName(); otherName1()); also isn’t valid syntax.

Related

Why getting too many re-renders error in react? [duplicate]

I have the following function
function hello() {
alert("hi!");
}
Take this piece of code:
var elem = document.getElementById("btn");
elem.onclick = hello;
My question might be a bit hard to understand, so bear with me:
What EXACTLY differentiates THIS piece of code from a normal call, or what makes this piece of code require a reference to the function variable rather than a regular call? (hello();)
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Well, the onclick property expects a reference to a function, for it to execute when the element is clicked. Normally it's either:
element.onclick = funcRef;
or
element.onclick = function () {
funcRef();
};
(but of course, it's best to use addEventListener and attachEvent)
Notice how both of them are references to functions, not calling.
When something expects a reference, you don't call it...you assign a reference to it (first example).
When you want to specifically call a function, you call it with () (second example). But notice how in the second example, there's still a reference to a function that's assigned to onclick - it's just an anonymous function.
Probably the more important part:
Some people think you want to do this:
element.onclick = funcRef();
But that immediately executes the function (because of the ()), and assigns its return value to onclick. Unless the return value is a function, this isn't what you want.
I think the moral of the story is that when you want/need something to execute right now, you call the function. If the function is wanted for later use or needs stored, you don't call it.
Do you want it to execute NOW? Then call it.
a=hello() means "Call hello() ASAP, and set its return value to a".
On the other hand, a=hello means "a is an alias for hello. If you call a(), you get the same results as calling hello()"
You use the latter for callbacks, etc, where you want to tell the browser what you want to happen after an event occurs. For example, you may want to say "call hello() when the user clicks" (as in the example). Or, "When the AJAX query returns a result, call the callback() function on the returned data".
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Do you need the function to run now?
Than add the () to execute it
Do you need to function to be referenced so it is called later?
Do not add the ().
Pretty much all statements in JavaScript have a return value. Unless otherwise specified, functions in JavaScript will return undefined when called. So, the only context in which it would make sense to call your function in this assignment statement if it were to return a function:
function hello() {
return function() {
alert("hi!");
}
}
elem.onclick = hello();
A reference to your function is needed somewhere no matter how it gets called. The difference here is that you are not explicitly calling the hello function. You are assigning a reference to that function to the elem DOM node's onclick event handler so that when onclick is fired for that Node, your function gets called.
hello() means you call that function, which means the function will be executed directly.
while when you have elem.onclick = hello, this is called a callback. Where hello doesn't get executed directly but only when a certain event is fired (in this case when there's a click on the element)

Node.js passport.use() function: TypeError: Cannot read properties of undefined (reading 'use') [duplicate]

I have the following function
function hello() {
alert("hi!");
}
Take this piece of code:
var elem = document.getElementById("btn");
elem.onclick = hello;
My question might be a bit hard to understand, so bear with me:
What EXACTLY differentiates THIS piece of code from a normal call, or what makes this piece of code require a reference to the function variable rather than a regular call? (hello();)
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Well, the onclick property expects a reference to a function, for it to execute when the element is clicked. Normally it's either:
element.onclick = funcRef;
or
element.onclick = function () {
funcRef();
};
(but of course, it's best to use addEventListener and attachEvent)
Notice how both of them are references to functions, not calling.
When something expects a reference, you don't call it...you assign a reference to it (first example).
When you want to specifically call a function, you call it with () (second example). But notice how in the second example, there's still a reference to a function that's assigned to onclick - it's just an anonymous function.
Probably the more important part:
Some people think you want to do this:
element.onclick = funcRef();
But that immediately executes the function (because of the ()), and assigns its return value to onclick. Unless the return value is a function, this isn't what you want.
I think the moral of the story is that when you want/need something to execute right now, you call the function. If the function is wanted for later use or needs stored, you don't call it.
Do you want it to execute NOW? Then call it.
a=hello() means "Call hello() ASAP, and set its return value to a".
On the other hand, a=hello means "a is an alias for hello. If you call a(), you get the same results as calling hello()"
You use the latter for callbacks, etc, where you want to tell the browser what you want to happen after an event occurs. For example, you may want to say "call hello() when the user clicks" (as in the example). Or, "When the AJAX query returns a result, call the callback() function on the returned data".
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Do you need the function to run now?
Than add the () to execute it
Do you need to function to be referenced so it is called later?
Do not add the ().
Pretty much all statements in JavaScript have a return value. Unless otherwise specified, functions in JavaScript will return undefined when called. So, the only context in which it would make sense to call your function in this assignment statement if it were to return a function:
function hello() {
return function() {
alert("hi!");
}
}
elem.onclick = hello();
A reference to your function is needed somewhere no matter how it gets called. The difference here is that you are not explicitly calling the hello function. You are assigning a reference to that function to the elem DOM node's onclick event handler so that when onclick is fired for that Node, your function gets called.
hello() means you call that function, which means the function will be executed directly.
while when you have elem.onclick = hello, this is called a callback. Where hello doesn't get executed directly but only when a certain event is fired (in this case when there's a click on the element)

creating a stopwatch using javascript [duplicate]

I have the following function
function hello() {
alert("hi!");
}
Take this piece of code:
var elem = document.getElementById("btn");
elem.onclick = hello;
My question might be a bit hard to understand, so bear with me:
What EXACTLY differentiates THIS piece of code from a normal call, or what makes this piece of code require a reference to the function variable rather than a regular call? (hello();)
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Well, the onclick property expects a reference to a function, for it to execute when the element is clicked. Normally it's either:
element.onclick = funcRef;
or
element.onclick = function () {
funcRef();
};
(but of course, it's best to use addEventListener and attachEvent)
Notice how both of them are references to functions, not calling.
When something expects a reference, you don't call it...you assign a reference to it (first example).
When you want to specifically call a function, you call it with () (second example). But notice how in the second example, there's still a reference to a function that's assigned to onclick - it's just an anonymous function.
Probably the more important part:
Some people think you want to do this:
element.onclick = funcRef();
But that immediately executes the function (because of the ()), and assigns its return value to onclick. Unless the return value is a function, this isn't what you want.
I think the moral of the story is that when you want/need something to execute right now, you call the function. If the function is wanted for later use or needs stored, you don't call it.
Do you want it to execute NOW? Then call it.
a=hello() means "Call hello() ASAP, and set its return value to a".
On the other hand, a=hello means "a is an alias for hello. If you call a(), you get the same results as calling hello()"
You use the latter for callbacks, etc, where you want to tell the browser what you want to happen after an event occurs. For example, you may want to say "call hello() when the user clicks" (as in the example). Or, "When the AJAX query returns a result, call the callback() function on the returned data".
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Do you need the function to run now?
Than add the () to execute it
Do you need to function to be referenced so it is called later?
Do not add the ().
Pretty much all statements in JavaScript have a return value. Unless otherwise specified, functions in JavaScript will return undefined when called. So, the only context in which it would make sense to call your function in this assignment statement if it were to return a function:
function hello() {
return function() {
alert("hi!");
}
}
elem.onclick = hello();
A reference to your function is needed somewhere no matter how it gets called. The difference here is that you are not explicitly calling the hello function. You are assigning a reference to that function to the elem DOM node's onclick event handler so that when onclick is fired for that Node, your function gets called.
hello() means you call that function, which means the function will be executed directly.
while when you have elem.onclick = hello, this is called a callback. Where hello doesn't get executed directly but only when a certain event is fired (in this case when there's a click on the element)

Arrow function in onClick method? [duplicate]

I have the following function
function hello() {
alert("hi!");
}
Take this piece of code:
var elem = document.getElementById("btn");
elem.onclick = hello;
My question might be a bit hard to understand, so bear with me:
What EXACTLY differentiates THIS piece of code from a normal call, or what makes this piece of code require a reference to the function variable rather than a regular call? (hello();)
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Well, the onclick property expects a reference to a function, for it to execute when the element is clicked. Normally it's either:
element.onclick = funcRef;
or
element.onclick = function () {
funcRef();
};
(but of course, it's best to use addEventListener and attachEvent)
Notice how both of them are references to functions, not calling.
When something expects a reference, you don't call it...you assign a reference to it (first example).
When you want to specifically call a function, you call it with () (second example). But notice how in the second example, there's still a reference to a function that's assigned to onclick - it's just an anonymous function.
Probably the more important part:
Some people think you want to do this:
element.onclick = funcRef();
But that immediately executes the function (because of the ()), and assigns its return value to onclick. Unless the return value is a function, this isn't what you want.
I think the moral of the story is that when you want/need something to execute right now, you call the function. If the function is wanted for later use or needs stored, you don't call it.
Do you want it to execute NOW? Then call it.
a=hello() means "Call hello() ASAP, and set its return value to a".
On the other hand, a=hello means "a is an alias for hello. If you call a(), you get the same results as calling hello()"
You use the latter for callbacks, etc, where you want to tell the browser what you want to happen after an event occurs. For example, you may want to say "call hello() when the user clicks" (as in the example). Or, "When the AJAX query returns a result, call the callback() function on the returned data".
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Do you need the function to run now?
Than add the () to execute it
Do you need to function to be referenced so it is called later?
Do not add the ().
Pretty much all statements in JavaScript have a return value. Unless otherwise specified, functions in JavaScript will return undefined when called. So, the only context in which it would make sense to call your function in this assignment statement if it were to return a function:
function hello() {
return function() {
alert("hi!");
}
}
elem.onclick = hello();
A reference to your function is needed somewhere no matter how it gets called. The difference here is that you are not explicitly calling the hello function. You are assigning a reference to that function to the elem DOM node's onclick event handler so that when onclick is fired for that Node, your function gets called.
hello() means you call that function, which means the function will be executed directly.
while when you have elem.onclick = hello, this is called a callback. Where hello doesn't get executed directly but only when a certain event is fired (in this case when there's a click on the element)

what is the difference between these two

I'm very new to js so I'd appreciate some help. I have two blocks of code that I think should work identically but don't. Can someone explain how they're different? It looks like in the first piece of code, the parser enters the function directly.
function embedGameSwfAfterReg() {
embedGameSwf("{$swfLocation}", "100%", "100%", {$flashVars});
}
API.registerOnload(embedGameSwfAfterReg())
and
API.registerOnload(function() {
embedGameSwfAfterReg("{$swfLocation}", "100%", "100%", {$flashVars});
});
In the first code block, you're registering the result of the embedGameSwfAfterReg function (undefined) as the onload function (() means you're evaluating the function). Remove the parentheses to have the embedGameSwfAfterReg function itself registered:
API.registerOnload(embedGameSwfAfterReg)
This
API.registerOnload(embedGameSwfAfterReg())
runs embedGameSwfAfterReg, and then passes the return value (undefined since it doesn't return a value), to registerOnLoad
you want
API.registerOnload(embedGameSwfAfterReg)
which passes the function itself to registerOnload
Functions are objects in Javascript and can be passed directly by their names. When you add the parens, it instead runs the function and passes the result.
function embedGameSwfAfterReg() {
embedGameSwf("{$swfLocation}", "100%", "100%", {$flashVars});
}
API.registerOnload(embedGameSwfAfterReg)
and
API.registerOnload(function() {
embedGameSwfAfterReg("{$swfLocation}", "100%", "100%", {$flashVars});
});
would work the same way.
The difference is () which you have put with embedGameSwfAfterReg function in the first case
It actually calls the function there only but its different in the 2nd case.
I'm asssuming that the second example should be
API.registerOnload(function() {
embedGameSwf("{$swfLocation}", "100%", "100%", {$flashVars});
});
If so, then the difference is quite big. In the first case, the embedGameSwfAfterReg function is invoked and the embedGameSwf is called when you register. This is probably not what you want since the the return value of the function is undefined.
In the second case, the anonymous function is not invoked until later when the registerOnLoad event is raised. This is probably what you want.
API.registerOnload() takes a callback function as parameter, therefore you only have to pass in the function name as reference, otherwise the function is directly getting called when the code runs.
// Correct form is:
API.registerOnload(embedGameSWFAfterReg)
Your second sample already is an anonymous function that is handled like an function callback and therefore evaluated when API.registerOnload(callback) is calling the reference with callback() somewhere inside it's code.
Short answer:
First piece of code do nothing, because embedGameSwfAfterReg doesn't have a return statement. Probably it could even end up with an error if API.registerOnload doesn't accurately check its arguments before execution.
Second piece of code creates an anonymous-function that is passed as an argument to API.registerOnload method which (as far as I can see from method name) runs functions during an Onload event.
Long answer:
In the first piece of code you declare a new function named embedGameSwfAfterReg which resists in global-scope of your code:
function embedGameSwfAfterReg() {
// calls embedGameSwf function
}
after, you execute defined function and pass the result to registerOnload method of an object named API:
API.registerOnload(embedGameSwfAfterReg());
As you probably mentioned, declared function embedGameSwfAfterReg has no return statement, so the result of its execution will be undefined. In other words
API.registerOnload(embedGameSwfAfterReg());
is doing the same as
embedGameSwfAfterReg();
API.registerOnload();
so eventually it calls API.registerOnload() WITHOUT any arguments passed!
Second piece of code creates an anonymous function (functions are specific objects in JS, which can be passed to other functions/methods, have its own methods and executed). Then it passes created function (or better say a reference to the function) to registerOnload - method of an object called "API".
You should read topics about Objects, Function-type, scopes, anonymous functions and closures in JS. I would advise Mozilla JavaScript guide
Also feels free to play with a simplified example at jsfiddle which gives some practical hint on anonymous functions in JS.

Categories