Javascript invoke function without parentheses [duplicate] - javascript

How do I pass a function as a parameter without the function executing in the "parent" function or using eval()? (Since I've read that it's insecure.)
I have this:
addContact(entityId, refreshContactList());
It works, but the problem is that refreshContactList fires when the function is called, rather than when it's used in the function.
I could get around it using eval(), but it's not the best practice, according to what I've read. How can I pass a function as a parameter in JavaScript?

You just need to remove the parenthesis:
addContact(entityId, refreshContactList);
This then passes the function without executing it first.
Here is an example:
function addContact(id, refreshCallback) {
refreshCallback();
// You can also pass arguments if you need to
// refreshCallback(id);
}
function refreshContactList() {
alert('Hello World');
}
addContact(1, refreshContactList);

If you want to pass a function, just reference it by name without the parentheses:
function foo(x) {
alert(x);
}
function bar(func) {
func("Hello World!");
}
//alerts "Hello World!"
bar(foo);
But sometimes you might want to pass a function with arguments included, but not have it called until the callback is invoked. To do this, when calling it, just wrap it in an anonymous function, like this:
function foo(x) {
alert(x);
}
function bar(func) {
func();
}
//alerts "Hello World!" (from within bar AFTER being passed)
bar(function(){ foo("Hello World!") });
If you prefer, you could also use the apply function and have a third parameter that is an array of the arguments, like such:
function eat(food1, food2) {
alert("I like to eat " + food1 + " and " + food2 );
}
function myFunc(callback, args) {
//do stuff
//...
//execute callback when finished
callback.apply(this, args);
}
//alerts "I like to eat pickles and peanut butter"
myFunc(eat, ["pickles", "peanut butter"]);

Example 1:
funct("z", function (x) { return x; });
function funct(a, foo){
foo(a) // this will return a
}
Example 2:
function foodemo(value){
return 'hello '+value;
}
function funct(a, foo){
alert(foo(a));
}
//call funct
funct('world!',foodemo); //=> 'hello world!'
look at this

To pass the function as parameter, simply remove the brackets!
function ToBeCalled(){
alert("I was called");
}
function iNeedParameter( paramFunc) {
//it is a good idea to check if the parameter is actually not null
//and that it is a function
if (paramFunc && (typeof paramFunc == "function")) {
paramFunc();
}
}
//this calls iNeedParameter and sends the other function to it
iNeedParameter(ToBeCalled);
The idea behind this is that a function is quite similar to a variable. Instead of writing
function ToBeCalled() { /* something */ }
you might as well write
var ToBeCalledVariable = function () { /* something */ }
There are minor differences between the two, but anyway - both of them are valid ways to define a function.
Now, if you define a function and explicitly assign it to a variable, it seems quite logical, that you can pass it as parameter to another function, and you don't need brackets:
anotherFunction(ToBeCalledVariable);

There is a phrase amongst JavaScript programmers: "Eval is Evil" so try to avoid it at all costs!
In addition to Steve Fenton's answer, you can also pass functions directly.
function addContact(entity, refreshFn) {
refreshFn();
}
function callAddContact() {
addContact("entity", function() { DoThis(); });
}

I chopped all my hair off with that issue. I couldn't make the examples above working, so I ended like :
function foo(blabla){
var func = new Function(blabla);
func();
}
// to call it, I just pass the js function I wanted as a string in the new one...
foo("alert('test')");
And that's working like a charm ... for what I needed at least. Hope it might help some.

I suggest to put the parameters in an array, and then split them up using the .apply() function. So now we can easily pass a function with lots of parameters and execute it in a simple way.
function addContact(parameters, refreshCallback) {
refreshCallback.apply(this, parameters);
}
function refreshContactList(int, int, string) {
alert(int + int);
console.log(string);
}
addContact([1,2,"str"], refreshContactList); //parameters should be putted in an array

You can also use eval() to do the same thing.
//A function to call
function needToBeCalled(p1, p2)
{
alert(p1+"="+p2);
}
//A function where needToBeCalled passed as an argument with necessary params
//Here params is comma separated string
function callAnotherFunction(aFunction, params)
{
eval(aFunction + "("+params+")");
}
//A function Call
callAnotherFunction("needToBeCalled", "10,20");
That's it. I was also looking for this solution and tried solutions provided in other answers but finally got it work from above example.

Here it's another approach :
function a(first,second)
{
return (second)(first);
}
a('Hello',function(e){alert(e+ ' world!');}); //=> Hello world

In fact, seems like a bit complicated, is not.
get method as a parameter:
function JS_method(_callBack) {
_callBack("called");
}
You can give as a parameter method:
JS_method(function (d) {
//Finally this will work.
alert(d)
});

The other answers do an excellent job describing what's going on, but one important "gotcha" is to make sure that whatever you pass through is indeed a reference to a function.
For instance, if you pass through a string instead of a function you'll get an error:
function function1(my_function_parameter){
my_function_parameter();
}
function function2(){
alert('Hello world');
}
function1(function2); //This will work
function1("function2"); //This breaks!
See JsFiddle

Some time when you need to deal with event handler so need to pass event too as an argument , most of the modern library like react, angular might need this.
I need to override OnSubmit function(function from third party library) with some custom validation on reactjs and I passed the function and event both like below
ORIGINALLY
<button className="img-submit" type="button" onClick=
{onSubmit}>Upload Image</button>
MADE A NEW FUNCTION upload and called passed onSubmit and event as arguments
<button className="img-submit" type="button" onClick={this.upload.bind(this,event,onSubmit)}>Upload Image</button>
upload(event,fn){
//custom codes are done here
fn(event);
}

By using ES6:
const invoke = (callback) => {
callback()
}
invoke(()=>{
console.log("Hello World");
})

If you can pass your whole function as string, this code may help you.
convertToFunc( "runThis('Micheal')" )
function convertToFunc( str) {
new Function( str )()
}
function runThis( name ){
console.log("Hello", name) // prints Hello Micheal
}

You can use a JSON as well to store and send JS functions.
Check the following:
var myJSON =
{
"myFunc1" : function (){
alert("a");
},
"myFunc2" : function (functionParameter){
functionParameter();
}
}
function main(){
myJSON.myFunc2(myJSON.myFunc1);
}
This will print 'a'.
The following has the same effect with the above:
var myFunc1 = function (){
alert('a');
}
var myFunc2 = function (functionParameter){
functionParameter();
}
function main(){
myFunc2(myFunc1);
}
Which is also has the same effect with the following:
function myFunc1(){
alert('a');
}
function myFunc2 (functionParameter){
functionParameter();
}
function main(){
myFunc2(myFunc1);
}
And a object paradigm using Class as object prototype:
function Class(){
this.myFunc1 = function(msg){
alert(msg);
}
this.myFunc2 = function(callBackParameter){
callBackParameter('message');
}
}
function main(){
var myClass = new Class();
myClass.myFunc2(myClass.myFunc1);
}

Related

javascript two brackets after function name

What does below syntax means?
connect(mapStateToProps, mapDispatchToProps)(Home)
I understand we are passing two arguments to a function, but what is the purpose of below one?
(Home)
It doesn't look like node but Redux and as in a comment not an ES6 thing.
What it is: Connect is a higher order (factory) function ie. it returns a function. And it is that returned function which is immediately called with Home
Take a look and an example of mock of connect below
function connect(param1, param2) {
return innerFunction (innerParam) {
console.log(`${param1} ${innerParam} ${param2}`)
}
}
connect('A','B')('precedes')
// outputs 'A precedes B'
Edit: Added an example.
A function can return a function, and you can call this returned function immediately.
For information and as already stated in comments, the fact of decomposing one function call into smaller like this one in your example is called currying and is a common practice in JavaScript (more info here : What is 'Currying'?)
This example might help you :
function function1(info) {
return function(innerParam) {
console.log(`Hello this function has info ${info} and has just been called with this param: ${innerParam}` )
}
}
function1('Bobby')('Alice');
// same as :
var bobbyFunction = function1('Bobby');
bobbyFunction('Alice');
This is useful to dynamically generate a function that depends on some parameter, but can still be called several time with some other changing parameters. Imagine this, for instance :
var bobbyFunction = function1('Bobby');
['Alice', 'Tommy', 'Johny'].forEach(name => bobbyFunction(name));
It's plain javascript. Function connect returns another function and code immediately calls it with parameter Home.
function first(f) {
return function second(s) {
console.log(f, s);
}
}
// this
first('one')('two');
// is same as this
var x = first('one');
x('two');
see this example:
connect(mapStateToProps, mapDispatchToProps)(Home)// just like code below
function f(){
//do something
}
function connect(a,b){
return f;
}
connect(mapStateToProps, mapDispatchToProps);//first,return f;
connect(mapStateToProps, mapDispatchToProps)(Home)//second,return f(home);

JS function inside function:

Can i do smth like this?
function calltime(gmt,ajaxfile){
//do something with vars gmt & ajaxfile...
function (){
alert(gmt+ajaxfile);
}
}
as you may notice I want the inner function without a name to use arguments of a parent without sending them directly as arguments, Is it possible or is there the other way (without creating completely separate function)?
function calltime(gmt,ajaxfile){
//do something with vars gmt & ajaxfile...
return function (){
alert(gmt+ajaxfile);
}
}
//you can call like this
calltime('Hello', 'there')();
//you can call like this also
var callit = calltime('Hello', 'there');
callit();
If you are creating a function inside a function you are creating a clouser. so that you can access that inner function later and you can use outer function arguments and variables(scope) in the inner functions whenever you want. so you no need to pass argument to the inner function.
Here's one way to get it to work. These methods will have self invoking inside. If you don't want them to invoke when calling calltime, then you can look at #harry's answer, which returns the inner function instead of invoking it.
var calltime = function(gmt, ajaxfile) {
(function (g, a){
alert(g + a);
})(gmt, ajaxfile);
};
calltime('Hello ', 'there');
But if you really don't want to specify arguments, you can just straight up do this:
var calltime = function(gmt, ajaxfile) {
(function (){
alert(gmt + ajaxfile);
})();
};
calltime('Hello ', 'there');
The inside function will self invoke itself. You can copy and paste this into chrome inspector to test.
And one more, since we're talking about self invocation, might as well invoke everything about your question!
(function calltime(gmt, ajaxfile) {
(function (){
alert(gmt + ajaxfile);
})();
})('Hello ', 'there');
Edit: one more version that takes in numerous arguments.
var calltime = function () {
(function () {
var args = Array.prototype.slice.call(arguments);
alert(args.join(' ')); // outputs 'hello there friend'
}).apply(this, arguments);
};
calltime('hello', 'there', 'friend');
function calltime(gmt,ajaxfile){
//do something with vars gmt & ajaxfile...
var a = function (){
alert(gmt+ajaxfile);
}
}
calltime('a','b');
You can do it like so.

call to a function that inside another function in JavaScript

I want to call a function that is in another function.
example for the functions:
function funcOne() {
function funcTwo() { // i want to call to this function
//do something
}
}
I need to call to funcTwo function, when I click on a button which is outside of these two functions
how can i do it?
No, You can't call unless you return that function.
Function2 is private to function1.
you use
function funcOne() {
return {
funcTwo :function() { // i want to call to this function
//do something
}
}
}
EDIT: Structuring code
function funcOne() {
var funcTwo = function() { // private function
//do something
}
return {
funcTwo : funcTwo
}
}
Now you can call it as:
funcOne().funcTwo()
As you have it defined in your example, you can't. funcTwo is scoped inside of funcOne, so it can only be called from inside funcOne. You can assign funcTwo to a variable that is scoped outside of funcOne and that would work:
var funcRef;
function funcOne() {
funcRef = function funcTwo() {
}
}
In this case, funcRef would hold a reference and could be used, but that reference is only set once funcOne has been executed.
Reading some Douglas Crockford may help you understand...
Try recoding as:
function funcOne() {
this.funcTwo = function() {
}
}
I think you'd have to declare an instance of a funcOne object and then call the funcTwo method of that object. I'm a bit busy at the moment so I can't refine this answer at the moment.
It is not possible as the second function will be created just when the first function is called. it is not existent prior to that.
You would have to define it outside the first function like so:
function funcOne() {
}
function funcTwo() { // i want to call to this function
//do something
}
Or you could also call the first function and return the second function like this:
function funcOne() {
function funcTwo() { // i want to call to this function
//do something
}
return functTwo;
}
And then call it like this:
var f = funcOne();
f();

Function calling in Javascript with double brackets

When I call function hi()() with double brackets the function displays hi output and it will also give error saying, that hi is not function.
<html>
<head></head>
<script>
function hello()
{
document.write("hello");
}
function hi()
{
document.write("hi");
return "hello";
}
hi()();
</script>
</html>
What is the meaning of using ()() with function name?
The double parenthesis would have been useful if hi had returned a function instead of its name, like in
function hi(){
return hello;
}
hi()();
That's probably what was the intent.
Putting () after something that evaluates to a function will call that function. So, hi() calls the function hi. Assuming hi returns a function then hi()() will call that function.
Example:
function hi(){
return function(){return "hello there";};
}
var returnedFunc = hi(); // so returnedFunc equals function(){return "hello there";};
var msg = hi()(); // so msg now has a value of "hello there"
If hi() doesn't return a function, then hi()() will produce an error, similar to having typed something like "not a function"(); or 1232();.
()() means calling a function and if returns another function second parenthesis will call it.Please find below example :
function add(x){
return function(y){
return x+y;
}
}
add(3)(4)
output: 7
in above case add(4) will be called for add function and add(3) will be called for returned function. here value of parameter x is 3 and parameter y is 4.
Please note : we use parenthesis for function call.
The return value of this function is a string which is not a callable object.
function hi()
{
document.write("hi");
return "hello"; // <-- returned value
}
But if you want to call this function multiple times you can use a for-loop or some things else.
Example of hi()():
function hi(){
return function(){ // this anonymous function is a closure for hi function
alert('some things')
}
}
JS Fiddle: here
If you want to call hello function immediately after hi try this:
function hi()
{
document.write("hi");
return hello; //<-- no quote needed
// In this context hello is function object not a string
}
You can use eval() to execute it even if it's string : eval(hi()+'()');

Passing a function as an argument in a javascript function

I was wondering whether this is legal to do. Could I have something like:
function funct(a, foo(x)) {
...
}
where a is an array and x is an integer argument for another function called foo?
(The idea is to have one function that uses a for loop on the array, and calls that function in the params for every element in the array. The idea is so call this on different functions so elements of two arrays are multiplied and then the sums are added together. For example A[0] * B[0] + A[1] * B[1].)
I think this is what you meant.
funct("z", function (x) { return x; });
function funct(a, foo){
foo(a) // this will return a
}
This is not the way to declare a function with another function as one of it's parameters. This is:
function foodemo(value){
return 'hello '+ value;
}
function funct(a, foo) {
alert(foo(a));
}
//call funct
funct('world!', foodemo); //=> 'hello world!'
So, the second parameter of funct is a reference to another function (in this case foodemo). Once the function is called, it executes that other function (in this case using the first parameter as input for it).
The parameters in a function declaration are just labels. It is the function body that gives them meaning. In this example funct will fail if the second parameter wasn't provided. So checking for that could look like:
function funct(a, foo) {
if (a && foo && typeof a === 'string' && typeof foo === 'function'){
alert(foo(a));
} else {
return false;
}
}
Due to the nature of JS, you can use a direct function call as parameter within a function call (with the right function definition):
function funct2(foo){
alert(foo);
}
funct2(foodemo('world!')); //=> 'hello world!'
If you want to pass a function, just reference it by name without the parentheses:
function funct(a, foo) {
...
}
But sometimes you might want to pass a function with arguments included, but not have it called until the callback is invoked. To do this, when calling it, just wrap it in an anonymous function, like this:
funct(a, function(){foo(x)});
If you prefer, you could also use the apply function and have a third parameter that is an array of the arguments, like such:
function myFunc(myArray, callback, args)
{
//do stuff with myArray
//...
//execute callback when finished
callback.apply(this, args);
}
function eat(food1, food2)
{
alert("I like to eat " + food1 + " and " + food2 );
}
//will alert "I like to eat pickles and peanut butter"
myFunc([], eat, ["pickles", "peanut butter"]);
And what would you like it to achieve? It seems you mixed up a function declaration with a function call.
If you want to pass another calls result to a function just write funct(some_array, foo(x)). If you want to pass another function itself, then write funct(some_array, foo). You can even pass a so-called anonymous function funct(some_array, function(x) { ... }).
I would rather suggest to create variable like below:
var deleteAction = function () { removeABC(); };
and pass it as an argument like below:
removeETC(deleteAction);
in removeETC method execute this like below:
function removeETC(delAction){ delAction(); }
What you have mentioned is legal. Here, foo(X) will get called and its returned value will be served as a parameter to the funct() method
In fact, seems like a bit complicated, is not.
get method as a parameter:
function JS_method(_callBack) {
_callBack("called");
}
You can give as a parameter method:
JS_method(function (d) {
//Finally this will work.
alert(d)
});

Categories

Resources