Functions

Functions are an abstraction. A sequence of code that is given a name, you may think of them as mini or sub-programs. We make and use functions for a number of reasons, including:

Functions in JavaScript are defined with the function keyword. Given:

function foo(a, b) { return a+b; }

examples:

function ma(a, b, c) { return a*b + c; } var v = ma(1,2,3) + ma(3,4,5); v = (1*2+3) + (3*4+5); v = 5 + 17; v = 22;

function hello() { console.log("Hello, world!"); console.log("Hello, world!"); console.log("Hello, world!"); }

This function just prints "Hello, world!" to the console log 3 times and does nothing else. It does not even return a value. This kind of function is often called a procedure, it's used to abstract code into simpler to understand bite-sized chunks or to eliminate code repetition. It would be used like so:

// Prints out "Hello, world!" 9 times: hello(); hello(); hello();

Anonymous functions:

These are functions that are created without a name, they can be assigned to a variable, so that it has a name. Often they're just passed to a function as a "callback" function a function that the other function uses.
example:

var add = function(a, b) { // Note that there is no name following function. return a + b; }; // The function is used in the normal way: console.log(add(1,2));

Variables and Scope:

The scope of a variable is it's visibility to various areas inside the program.

Variables declared with "var" inside of functions are local to the function. That is they are only visible or members of the function and don't exist outside of the function. This includes the argument variables.

Variables declared outside of the function are global and are visible inside of all functions.

var g = 1; function foo(a, b) { g = a+b; } console.log(g); // prints out 1; foo(2,3); console.log(g); // prints out 5;