0

Generally whenever we're programming in any Programming language, say C, we would pass the parameters we need to pass to a function using the parentheses next to the name of the function. Whereas in jQuery, other than the user defined function() we write the action we need the function to perform inside the parentheses, for example,

$('div').mouseenter(function(){
   /* blah blah blah*/
});

Why?

3
  • When you say action to perform, do you mean the body of the anonymous function?
    – DFord
    Commented Oct 16, 2013 at 18:41
  • 4
    Short answer: because the action we need it to perform is a parameter.
    – Telastyn
    Commented Oct 16, 2013 at 18:48
  • @DFord Yes. The function specified performs the action we need to take place when the mouse enters the div here.
    – ikartik90
    Commented Oct 16, 2013 at 19:35

5 Answers 5

5

This is because the jQuery method mouseenter is expecting a single parameter, which is a function. It can then call that function later.

We could just as easily write

function blah(){
    /* blah blah blah */
}
$("div").mouseenter(blah);
5
  • 1
    That's the whole point. We're passing a function as a parameter to another function. Why is that? What's the whole significance?
    – ikartik90
    Commented Oct 16, 2013 at 19:50
  • 3
    Uhhhh, because the function is going to be executed an an indeterminate future moment, or possibly never? That's not a jQuery thing either, it's far more general as a Javascript pattern.
    – Darien
    Commented Oct 16, 2013 at 20:34
  • 3
    @ikartik90: Have a look at "first-class functions" in Wikipedia. Passing around functions is a method of indirection for behaviors. Among other things, having first-class functions allows you to hook up program behavior to some event like a mouse click, so that you can assign behavior to that event, rather than it being hardcoded to the event itself. Commented Oct 16, 2013 at 21:28
  • @RobertHarvey I would prefer to use a function as a parameter in a scenario where I would be recalling the parametrized function, say from another event. Whereas when I'm directly performing an action based on a certain event, I would prefer hard-coding the action inside the event itself. Isn't that significant considering that a concept called polymorphism exists?
    – ikartik90
    Commented Oct 19, 2013 at 7:38
  • 1
    @ikartik90: Think of the event system in a UI as a patch bay. When you want to enable some behavior for an event, you patch it to a method, and it executes that method when the event is fired. It doesn't matter whether you're patching several event handlers to a method, or just one. Why would you want to do it two different ways? Polymorphism is deciding which method to call based on the method signature; it doesn't have anything to do with this. Commented Oct 19, 2013 at 16:22
2

This is less about jquery, and more about how javascript works overall. Passing functions as variables is extremely vital to programming in javascript because javascript is asychronous. Consider this:

 var a = getA();
 var b = getB(a);

Now, we need 'a' first, then we use it to get 'b'. But javascript doesn't guarantee that function getA will run to completion before function getB is called. So we could do something like this instead:

 var b = getA(getB);

Now function getA can call getB when it's finished.

In your example (i didn't look it up but I'm assuming) you want the program to look at every div on the page, and when a mouse enters that div, execute a block of code.

We don't want that code to execute right away, on every div as soon as jquery finds it. We want the div to call that block of code when the mouse enters it. What do we call a block of code that can be called? We call that a function, son. So it wouldn't make sense to use anything other than a function.

13
  • your answer is incorrect. Javascript is a language, and has no notion of synchronicity, so to say it's asynchronous is in itself giving it an attribute that doesn't apply to a language. With that said, all browsers execute code in a single thread, basically following a FIFO pattern. So your examples are equivalent. both will result in the same execution path, and if you trace the code you'll find a and b are assigned in order in both cases. Commented Oct 17, 2013 at 3:53
  • 1
    @NicolásStraubValdivieso Asynchronous execution says nothing of threaded or parallel execution; all it means is that code is not guaranteed to run in the order you expect - whether or not this is in the same thread or different threads does not matter. DOM events, AJAX callbacks, and setTimeout/setInterval are just different ways to trigger it. Large swaths of Javascript are written asynchronously, and it is perfectly valid to call Javascript an asynchronous (but not parallel nor threaded) language because of this.
    – Izkata
    Commented Oct 21, 2013 at 3:24
  • 1
    @Izkata that's true but my original point/nitpick was that this has nothing to do with the language and everything to do with the environment where it executes. It's like saying C# is threaded. It's not... it's imperative and object oriented... .Net is threaded (or can be threaded) and provides the necessary execution environment and tooling to execute C# code in a threaded manner. If you read my first comment you'll see that what I wanted to point out is that both code samples provided are equivalent, regardless of whether you want to call javascript asynchronous or not Commented Oct 21, 2013 at 3:35
  • 1
    in other words what I'm trying to say is that synchronicity is not an attribute you can apply to javascript, or any language for that matter. It's like saying English is written and Spanish is spoken Commented Oct 21, 2013 at 3:39
  • 1
    yup, like I said in one of the previous comments, I was just being nitpicky :) Commented Oct 22, 2013 at 1:26
2

Let's rewrite your example a bit:

function mouseEnterAction() { doStuff(); }

$('div').mouseenter(mouseEnterAction);

The only difference here is that we're using a named function here rather than an unnamed function as you provided in your example.

Ask yourself - what is the "value" of an action? It isn't something simple like the number 5 or the string "Hello World". It isn't even something more complex like an array or an object. For an action to be performed, you need something capable of performing an action - in this case, a function.

The whole idea is you're setting up an event handler. When the event "mouseenter" happens, you execute the given function and perform whatever actions are needed. This isn't really fundamentally a Javascript/jQuery thing that's distinct from C - C can do things like this but the syntax is far more complicated.

0

Generally whenever we're programming in any Programming language, say C

C does not encompass "any programming language". For example it does not have Object Oriented capabilities. As a matter of fact, in C you'd do somethin similar to your JavaScript/JQuery example: pass a function as argument to your user input callback. Here's how it would work with GLUT:

void blah() {
   /* blah blah blah */
}

void ODLGameLoop_initOpenGL() {
    glutKeyboardFunc(blah);
}

In C and JavaScript functions are first class objects, meaning that they can, amongst other things, be passed around as arguments to other functions.

In Object Oriented languages, such as Java for example, you'd need to pass an instance of a certain type of class to the callback function, something like this:

class MyMouseListener implements MouseListener {

    public void mouseClicked(MouseEvent e) {
        /* blah blah blah */
    }


    public static void main(String[] args) {
        JFrame myJframe = ....;
        myJFrame.addMouseListener(new MyMouseListener());

    }

}

These are both examples of, as you put it: "we would pass the parameters we need to pass to a function using the parentheses next to the name of the function". It's just that in languages that support functions as first class objects, those parameters are (sometimes) functions, and in Object Oriented Languages they are (sometimes) objects.

0

Because the function that gets passed to the receiving function is throw away function, i.e. not reusable. If it was reusable, it would be written as a function (not closure) or a class method and you'd pass the function name instead of "write the action we need the function to perform inside the parentheses".

To clarify, the function body (action) is not written "inside the parentheses", it's written inside the curly braces which is part of the function(). i.e. the action is not part of mouseenter() but it belongs to function() that gets passed to mouseenter.

$('div').mouseenter(f);

f = function(){
   /* blah blah blah*/
};

It's no different to typical callback functions in Observer, just different style.

2
  • That's what I intend to ask you dude. When its a throw-away function, why do we need to code it in the first place? Why can't we just directly specify the action we need to perform and override the function every time we reuse it in a different context?
    – ikartik90
    Commented Oct 19, 2013 at 7:29
  • @ikartik90 I added some clarification. Though I'm not sure I understand your question. Overriding a function can have unexpected side effects (especially if they're part of a library), so it's easier to write a bunch of callback functions and register them to an event and if they're not reusable it's common to write them as closures.
    – imel96
    Commented Oct 21, 2013 at 0:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.