Function Expressions in JavaScript

Posted on
  • Is there anyone here who can point me at a really good introduction to function expressions in JavaScript. I have a basic understanding now, but am constantly tripping up and much of the example code here relies on this. As some fundamental level, I am failing to 'get it' !

    TIA

    Pat

  • I don't know any references for this - you really do need to understand how functions are defined, called, and used. I threw this together when I saw that there weren't any replies here - hope it's helpful (the meeting I was at was boooring...)

    //these two are the same:
    >function fun1(arg1) {return arg1+1;}
    >var fun1=function(arg1) {return arg1+1;}; //note the semicolon at the end of this - it's an assignment statement. 
    //now fun1 is a function, and you can treat it like any other variable - except that if you put parenthesis after it, that will call the function, and evaluate it appropriately. 
    
    >console.log(fun1)
    function fun1(arg1) {return arg1+1;}
    
    >console.log(fun1()); //will return NaN because undefined+1 is NaN)
    NaN 
    
    

    When you use functions as callbacks you refer to the function; you do not call it. If whatever's calling the callback function is supposed to pass arguments (like setWatch()), it will pass those arguments to the function, assuming the function accepts arguments.

    var func=function(a) {console.log(a);};
    
    setWatch(func, BTN, { repeat:true, edge:'falling' });
    //is the same as:
    setWatch(function(a) {console.log(a);}, BTN, { repeat:true, edge:'falling' });
    
    //Now this won't work, because here you're calling the function, and the value that it returns is used, and now the watch has no callback:
    
    setWatch(func(a), BTN, { repeat:true, edge:'falling' });
    
    //func(a) returns nothing, so it's like you were doing:
    
    setWatch(undefined, BTN, { repeat:true, edge:'falling' });
    
    
  • Hi, this is incredibly kind and very helpful. Fog begins to clear :)

    I think a hacking session or 10 will make this stick eventually!

    A million thanks.

    Pat

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Function Expressions in JavaScript

Posted by Avatar for Pat @Pat

Actions