Functions

Contact Us or call 1-877-932-8228
Functions

Functions

Functions contain blocks of code that need to be executed repeatedly. Functions can take zero or more arguments, and can optionally return a value.

Functions can be created in several ways.

Function Declaration

function functionName(parameterList) {
	/* do something */
}

Named Function Expression

var functionName = function(parameterList) {
	/* do something */
}

This approach creates an inline function, then assigns it to a variable. Since functions in JavaScript are also objects, they are treated as having a value, which can be stored in a variable, passed to a function, or returned from a function. When passed to a function as a parameter, or returned from a function, an inline function is also known as an anonymous function, since it does not have a name in the current section of code.

Using Functions

A Simple Function

var greet = function(person, greeting) {
	var text = greeting + ', ' + person;
	console.log(text);
};

greet('Rebecca', 'Hello');

A Function That Returns a Value

var greet = function(person, greeting) {
	var text = greeting + ', ' + person;
	return text;
};

console.log(greet('Rebecca','hello'));

A Function That Returns Another Function

var greet = function(person, greeting) {
	var text = greeting + ', ' + person;
	return function() { console.log(text); };
};

var task = greet('Rebecca','hello');
task();

// or
greet('Rebecca','hello') ();

Self-Executing Anonymous Functions

A common pattern in JavaScript is the self-executing anonymous function. 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 your code -- no variables declared inside of the function are visible outside of it.

A Self-Executing Anonymous Function

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

console.log(foo);   // undefined!

Functions as Arguments

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);
};

myFn( function() { return 'hello'; } );   // logs 'hello'

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);   // logs 'hello world'
Next