2

I am learning JavaScript and becoming confused by the logic of the code examples. From codecademy. Why are there function set-ups in function calls? I'm quite confused. I am moving from a simplified C-like langue.

The JavaScript example

var main = function(){
    $('.article').click(function(){
        $('.description').hide();

        $(this).children('.description').show();
    });
};

My understanding: - main is a function name with a return type of var.

  • $('.article') is a element/object/or class object.

  • .click() is a call to a member function

  • But:

???:

.click(function(){
    $('.description').hide();
    $(this).children('.description').show();
});

This seems to be a newly on the spot created function to run When/If click() is activated or run.

The way I used to think is like this:

 var *p_obj = $('.article');
 var *p_obj = $('.description');

 var do_click()
 {
     p_obj2.hide();
     p_obj.children(p_obj2).show();
 }

 var main(){
     p_obj.click(do_click);
 }

Function main() looks at p_obj and calls click().

Click() evaluates to true/false and run the pointer_to function do_click().

Function do_click() looks at the p_obj2 and calls hide(), which performs an action of hiding the p_obj2.

Function do_click() also looks at p_obj and uses children to scope focus to p_obj2, then it runs show(), which preforms an action of displaying p_obj2.

I do realize my C-like example is wrong and odd. I realize my terminology is wrong or otherwise used incorrectly.

The way this design looks seems like I must write extended functionality on-the-spot for every call to .click(), so if-then .click() is run on 3 different items, I'm creating different extended functionality for each object. But I would normally create a single function that varies it's internal execution based on the object or condition click() calls it by.

This set-up seems alright if the code a relatively simple or short, but on-the-spot functional seems like overworking for longer code and code where the functionality repeats but the objects change.

Am I thinking about JavaScript functions with-in functions correctly and is this a design goal of the langue to add long repeating extended functions with-in functions?

YakovL
  • 5,213
  • 10
  • 46
  • 71
Malice
  • 23
  • 4
  • `var do_click()` isn't valid...is either `funcion do_click(){` or `var do_click = function(){` – charlietfl Jun 25 '16 at 18:33
  • @charlietfl or `const do_click = () => { };` – Norguard Jun 25 '16 at 18:44
  • 2
    @Norguard no point mixing in es6 to complicate OP's issue though – charlietfl Jun 25 '16 at 18:45
  • @charliefl - I see that yes the c style is invalid for javascript and that is part of my problem having. As in `function do_click()` - function is and invalid return type for c or is a void type . -- C type return_type function_name( parameter list ) { body of the function }[link](http://www.tutorialspoint.com/cprogramming/c_functions.htm) – Malice Jun 25 '16 at 21:26

4 Answers4

2

Here, you should understand 2 things:

  1. passing functions as arguments
  2. anonymous functions

The first concept is particulary important because callbacks are popular in JavaScript, so let me explain it for callbacks. Imagine we have 2 functions getStuffFromWeb and processStuff. You probably expect that they are used like this:

var result = getStuffFromWeb();
processStuff(result);

But the issue here is waiting for getStuffFromWeb may take some time (the server is busy), so instead they are usually used in a "when you finish, call this function" manner, which is:

var getStuffFromWeb = function(params,callback) {
    ...
    callback(result);
};
getStuffFromWeb(someParams,processStuff);

Well, in fact the structure of getStuffFromWeb will be different, most likely something like this:

var getStuffFromWeb = function(params,callback) {
    requestObject.make_request(params)
                 .onSuccess(callback);
};

So when getStuffFromWeb is called, it starts to listen to response while the code after getStuffFromWeb(someParams,processStuff); goes on evaluating. When the response comes, it calls the callback function to process the data further using the procedure we have defined (processStuff).

The second concept is rather simple: you may of'course write smth like

var processStuff = function() {...};
var getStuffFromWeb = function(params,callback) {
    requestObject.make_request(params)
                 .onSuccess(callback);
};
getStuffFromWeb(someParams,processStuff);

but if you use processStuff only once, why define a named function? Instead, you can just put the very same expression inside the onSuccess param like this:

var getStuffFromWeb = function(params) {
    requestObject.make_request(params)
                 .onSuccess(function() {...});
};
getStuffFromWeb(someParams);

This looks exactly like if we took the value of processStuff and put it directly to the onSuccess's argument (and that's called anonymous function). And also we got rid of an extra argument of getStuffFromWeb.

So basically that's it.

YakovL
  • 5,213
  • 10
  • 46
  • 71
  • Thank you. The explanation of the missing concept is clear in your answer and now I understand. – Malice Jun 25 '16 at 21:48
1

Simple answer is that the second argument of click() requires a callback function.

This can be a named function passed as reference as in your p_obj.click(do_click); example or it can be an anonymous function with self contained logic. Anonymous functions are very common in javascript

It's the same thing just with 2 different ways of declaring the callback.

Note that the only time you would return anything from an event handler function would be to return false which effectively prevents the default browser event (url opening from href or form submit for examples) and stops event propagating up the DOM tree

charlietfl
  • 164,229
  • 13
  • 110
  • 143
  • Thank you. With this and all the feedback I understand now. The primer thinking changes are `var main` is a named var to something akin to the pointer for the function code, and `function ()` can be used to create an anonymous function if it isn't given a name. I'm no expert in C , however I've always had to name everything. – Malice Jun 25 '16 at 21:45
1

main is a function name with a return type of var.

No. main is a variable which is assigned an anonymous function. The function name would go between the keyword function and the () containing the argument list.

It has no return statement so it returns undefined.

$('.article') is a element/object/or class object.

It is a call to the function $ with one argument. The return value is a jQuery object.

.click() is a call to a member function

Pretty much. In JavaScript we call any function that is the value of a property of an object as method.

This seems to be a newly on the spot created function

function () { } is a function expression. It creates a function, exactly like the one used to assign a value to main earlier. This question is worth reading for more on the subject.

When/If click() is activated or run.

The click function is called immediately. The new function is passed as an argument.

The purpose of the click function is to bind a click event handler so that when a click event hits the element later on, it will trigger the function passed as an argument.

I do realize my c -like example is wrong and odd. I realize my terminology is wrong or otherwise used incorrectly.

Leaving aside vagaries of syntax. The main difference here is that the click event handler function is that the event handler function is stored in an intermediary variable.

You can do that in JavaScript just as easily, and then reuse the function elsewhere in the code.

var main = function(){

    function show_specific_description() {
        $('.description').hide();
        $(this).children('.description').show();
    }

    $('.article').click(show_specific_description);
    show_specific_description.call($(".article").last()[0]);
};

main();

is this a design goal of the langue to add long repeating extended functions with-in functions?

No. Passing a function expression as an argument is a convenient way to be more concise when you don't want to reuse the function. It's not the only way to pass functions about.

Community
  • 1
  • 1
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • Thank you that answer is very helpful. Is-then `var main =` akin to setting the var data-object to the value of the functions pointer? This is how I'm thinking. – Malice Jun 25 '16 at 21:52
0
  1. main is currently a function.
    It is possible to be overwritten (even to a different type). var is not the return type, it's a statement that main is a variable.
    All values should be declared as variables, within the highest scope you intend them to be used (in JS, scope typically means functions, not blocks).

  2. You have the right idea, suspecting that the function gets passed in, and called at a later point in time (and this is actually one of the harder parts for people to get, coming from certain other languages). You'll see this behaviour all through JS.

  3. One key thing to keep in mind in this language (you haven't hit it yet, but you will) is that JS is lexically scoped.

    function getInnerX () {
      var x = 5;
      function getX () {
        return x;
      };
      return getX;
    }
    
    var x = 10;
    var getX = getInnerX();
    console.log(getX()); // 5  
    

    The function getX inside of getInnerX has access to the references around it, at the point where it's defined (not where it's called), and thus has live access to the inner x, even if its value changes over time.
    This will be another important piece of understanding what you see going on in the language, especially in the case of callbacks.

Norguard
  • 24,349
  • 4
  • 38
  • 45