Functions, Heart of JavaScript !

Open Source 23 Mar , 2013  

Buffer

the-Function-Machine_05Functions are the central working units of JavaScript. Nearly every script you’ll write uses one or more functions. Therefore it is important that you understand what a function is and how it works.

First I explain the basic syntax, of a function, then I explain how to call it. After that you learn how to pass arguments and why you should do this. Finally, we make the function return something.

Functions can take zero or more arguments, and can optionally return a value.

Functions can be created in a variety of ways, two of which are shown below:

// Function declaration.
function myFunction() {
    /* do something */
}
// Named function expression.
var myFunction = function() {
    /* do something */
}

Calling a Function :

// A simple function.
var msg = function( person, greeting ) {
    var text = greeting + ", " + person;
    console.log( text );
};
msg( "Ankita", "Hi" );
// A function that returns a value.
var msg = function( person, greeting ){
  var text = greeting + ", " + person;
  return text;
};
console.log( ,sg( "Ankita", "Hi" ) ); // "Hi, Ankita"

Immediately-Invoked Function Expression (IIFE) :

javascript_function_05This is something which you will find very useful in near future when you learn jQuery. This is a common pattern in JavaScript is the immediately-invoked function expression. This pattern creates a function expression and then immediately executes the function. This pattern is extremely useful for cases where you want to avoid polluting the global namespace with code – no variables declared inside of the function are visible outside of it.

// An immediately-invoked function expression.

(function() {
    var foo = "Hello world";
})();

console.log( foo );   // undefined!

Functions as Arguments :

It is said that in JavaScript, functions are “first-class citizens” – they can be assigned to variables or passed to other functions as arguments. Passing functions as arguments is an extremely common idiom in jQuery.

// Passing an anonymous function as an argument.

var myFn = function( fn ) {
    var result = fn();
    console.log( result );
};

// logs "hello world"
myFn( function() {
    return "hello world";
});
// Passing a named function as an argument

var myFn = function( fn ) {
    var result = fn();
    console.log( result );
};

var myOtherFn = function() {
    return "hello world";
};

myFn( myOtherFn ); // "hello world"

So these were some example of how to use functions, they are very powerful and in future you will need to play with them so much, specially in jQuery, understanding function will help you so much, Enjoy!

, , , , ,