UPDATES VIA   RSS  |  Email Get updates via feedburner Get updates via twitter
Home / Coding / JavaScript & Ajax / JavaScript: Send function as…

JavaScript: Send function as a parameter to another function (callbacks)

Posted on 29. Jul, 2009 by Dragos in Coding, JavaScript & Ajax

I’m sure you’ve seen a lot of code where functions are send as parameters, usually working as function callbacks e.g:

setTimeout(function () { alert('test'); },1000);

But how does the function setTimeout execute the passed function as a parameter? The answer is simple, but I need to provide you an example to understand it ;)

Let’s create a simple function, accepting two parameters: first a boolean value, the second – a function. Our function will analyze the boolean parameter and in case the value is true, the function passed as a parameter will be executed.

function simpleFunc(bool,func) {
    if(bool) func();
}

As you notice, we add parentheses after the name of the second parameter, because we’ll treat it as a function. And that’s te whole secret.

Now that is how we will use the simpleFunc function:

simpleFunc(false,function() { alert('Yupee!'); }; // this won't alert anything, because the boolean parameter is false
//example two
simpleFunc(true,function() { alert('Yupee!'); }); // this will alert Yupee! :)

Wish you luck!

Translate this post
                    
                    

Related posts:

  1. Javascript: How to validate email address with JavaScript?
  2. JavaScript: How to get the index (position within a group) of an object with jQuery?
  3. JavaScript: What if jQuery animation doesn’t fire/start?
  4. Coding: How to get code suggestions and function completion in Netbeans?
  5. Coding:How to fetch user profile data with SSI.php from a SMF forum database

blog comments powered by Disqus