Skip to content

Instantly share code, notes, and snippets.

@supersym
Created December 20, 2012 23:04
Show Gist options
  • Save supersym/4349426 to your computer and use it in GitHub Desktop.
Save supersym/4349426 to your computer and use it in GitHub Desktop.

References:

This gist is a mash-up of the following article sources and credits to their respective posters: mike@recurial.com helen@helephant greg@thehellings jan@elegantcode

Functions are a very important concept in most programming languages, but they are even more important in JavaScript and especially callback functions play a special role. They’re found pretty much everywhere but in order to understand callback functions you first have to understand regular functions.

Some examples:

Self executing functions

(
  function() {
    alert("Hello Mars");
  }
)()

This basically is an anonymous function that is invoked immediately, caused by the last pair of parentheses. It’s also possible to specify arguments to the anonymous function like so:

(
  function(planet) {
    alert("Hello " +  planet);
  }
)("Jupiter")

Why is this useful? Well, you can do all sorts of stuff with self-executing functions like one-off initialization without having to mess around with global variables. They are also commonly used for variable scoping. Variables declared inside a self-executing function cannot be accessed from outside the function. This way it’s possible to provide proper encapsulation

Functions in Javascript are actually objects, they are treated as 'first class citizens'. This just means that javascript functions are a (special) type of object, of which object is just anything not a scalar value, and that can do all the things that regular objects can do and more. More specifically, they’re Function objects created with the Function constructor. JavaScript is not a ‘classical’ language but a prototypal object language, and as such a Function object contains a string which contains the Javascript code of the function.

One benefit of this function-as-object concept is that you can pass code to another function in the same way you would pass a regular variable or object (because the code is literally just an object).

// you can create a function by passing the
// Function constructor a string of code
var func_multiply = new Function("arg1", "arg2", "return arg1 * arg2;");
func_multiply(5,10); // => 50

A function is an instance of the Object type:

function feedCat(){
    alert("Kibble, tinned food and water");
}
alert(feedCat instanceof Object);

A function can have properties and has a link back to its constructor method:

feedCat.food = "kibble";
alert(feedCat.food);
alert(feedCat.constructor);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment