1

I just started programming and I've been playing around with it. I watched a programming course on lynda.com to start out, but it didn't cover functions very well, I know what they are, but I don't know the different formats of functions or how to call them. I know how to call simple things like this:

var foo=function {
    //code...
}

but I want to use more complicated things like this (I'm starting to to things with HTML):

$(document).keypress(function(e)) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
}); 

or just whatever other styles there are.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
CPC
  • 163
  • 5
  • 17
  • You should probably complete the tutorials or read a good book about Javascript. I recommend "The Definitive Guide" – Munim Jan 16 '14 at 08:20
  • Your first example is invalid, you have to add parenthesis after function : `var foo=function() { /* code... */ }`. Your second example is probably jQuery. It's not native javascript, it's a framework. You should learn pure javascript before using frameworks. – Sebastien C. Jan 16 '14 at 08:33

5 Answers5

2

There are no different formats of functions. All of them are defined with function keyword followed by arguments and body. If you have a function foo then you call it via foo(); (you can pass arguments as well, foo(1,2,3);). There are more complex ways of calling functions, for example via foo.call or foo.apply but I don't think it is necessary to talk about that here.

Note that functions in JavaScript are first class citizens. That means that they can be treated as objects. In particual you can pass them to another function. Have a look at this example:

var foo = function(fn) {
    return fn()+1;
};

What happens here? foo takes a function as an argument (we know that because fn() is called in body), calls it and adds 1 to result. So if I call foo like this:

foo(function() {
    return 1;
});

what would the result be? That's a simple example. Consider something more complex:

var foo = function(list, fn) {
    var res = [];
    for (var i = 0; i < list.length; i++) {
        var mapped = fn(list[i]);
        res.push(mapped);
    }
    return res;
};

This is a simple version of the .map method on lists. So it takes a list and a function as arguments, then applies the function to each element of the list and returns a new list:

> foo([1, 2, 3], function(el) { return -el; });
[-1, -2, -3]

It is the same as calling

> [1, 2, 3].map(function(el) { return -el; });
[-1, -2, -3]
freakish
  • 54,167
  • 9
  • 132
  • 169
1

Different ways of declaring functions

function A() {};            // function declaration

var B = function() {};      // function expression

var C = ( function() {} );  // function expression with grouping operators

var D = function foo() {};  // named function expression

var E = ( function() {      // immediately-invoke function expression (IIFE) that returns a function
  return function() {}
})();

var F = new Function();     // Function constructor

var G = new function() {};  // special case: object constructor
P82
  • 13
  • 6
0

Your code is actually a good example of the different types of functions. First is $(), which represents the JQuery library--a useful add-on to JavaScript. You typically give it a string called a CSS selector, which is a way to pick out a part (or parts) of a document. In this case, you're picking out the whole document, but you could also say something like $("#logo"), which will return a document with id="logo" or $("img") will return all elements in the document.

An object in JS can be just about anything, and there are different types of objects. Each type of object has special functions available to it. These functions are called methods.

In the above example, the document object returned by $(document) has the .keypress() method available to it, which listens for a particular keypress. Keypress needs to know what to do when a key is pressed, and you do so by giving it a function as a parameter. That function will execute every time a key is pressed.

One thing that's useful to remember about JavaScript is that functions are thought of as "first-class citizens", meaning they are as good as straight-up values as far as JavaScript is concerned. So if I have a function like:

    var myString = function(word)
    {
       return word;
    }

If I do:

     var myWord = "hello";

It's the same as:

     var otherWord = myString("hello");

If I compare them:

    var compareWords = function(word1, word2)
    {
        return word1 == word2;
    }

    var compareMyWords = compareWords(myWord, otherWord);

It's the same as saying

    var compareMyWords = true;

This is important to know because it means functions can take other functions as arguments without a problem. We see that happening in the keypress method. It might be a bit hard to notice, but you can see it if you declare the function beforehand:

var keypressFunction =  function(e)) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }

The following is the same as your example:

 $(document).keypress(keypressFunction);

The difference is that your example uses an anonymous function. It hasn't been declared with "var" or "function", so I couldn't reuse it if I wanted to. That's not really a bad thing. Anonymous functions are very useful when you get into more advanced stuff.

Your anonymous function is allowed one parameter, an object representing the key that was actually pressed. In this case it only wants to do something if the key represented by 13 is pressed (Enter).

Finally there's the alert function, which pops up a message. Note that functions don't always have to return a value. Usually when they don't, they do something to their environment instead (otherwise what's the point). In your example only one function actually returns something--the $() function, although nothing gets done with it, but you could keep going and replace the semicolon at the end with a period and use the ready() method or whatever methods are available to the object returned by $(document). In fact, as long as you know what type of object is being returned, you could do something like:

    $("#message").addClass("alert").fadeIn().delay().fadeOut();

Because each of these methods return the same object, we can do this "method chaining". jQuery purposely tries to make most of its methods return the DOM objects it acted on so that you can do this. Other libraries, like d3.js, make use of method chaining for some very cool visual transformations.

I don't think starting off using jQuery is as horrible an idea as others might advise. It's still JavaScript. It could be argued that JQuery forces you to learn advanced concepts (callbacks, CSS selectors, etc) that you could otherwise hobble by for years without knowing. I could also argue that JavaScript itself is a bad language to start with when learning to program.

Instead I'll say dive in and have fun! The ultimate purpose is to build awesome things & not get too crippled by having to do it the right way. Find a good balance between learning and building, and don't get too discouraged by the few jealous stackoverflow users who come here to snuff the joy they once had in building awesome things.

Chad Hedgcock
  • 11,125
  • 3
  • 36
  • 44
0

I order to know how to call different types of functions in Javascript it is important to know all JavaScript Function types. Below is a link that take you to:

All JavaScript Function Types?

S. Mayol
  • 2,565
  • 2
  • 27
  • 34
-1

I personally think you are over complicating it. Yes, the different ways of writing a function tend to have different names (function, anonymous function, colosure, lambda,....) but in the end its all a function: They combine several statements into one.

For example:

// Crating a function (most commomn way)
function a() { 
    alert('a'); 
};

// Creating a anonymous (nameless) function and assigning it to b
var b = function() { 
    alert('b'); 
};

var c = a;
var d = b;

var e = {}; 
// Creating a function that accepts a function and executes it.
// This is in essence what $(document).keypress() does
e.f = function(f){
    f();
};

// Alerts: a
a();

// Alerts: b
b();

// Alerts: a
c();

// Alerts: b
d();

// Sample how you can call $(document).keypress() 
// Alerts: c
e.f( function() {
    alert('c');
});

// Alerts: a
e.f(a);

// Alerts: b
e.f(b);
KillerX
  • 1,436
  • 1
  • 15
  • 23