Functions

Functions are reusable blocks of code that carry out a specific task. To execute the code in a function you call it. A function can be passed arguments to use, and a function may return a value to whatever called it.

To create a function, use the function keyword. You then list the arguments in parentheses, and then supply a block that contains the function’s code. Here’s a function that adds two numbers:

var add = function (a, b) {
    return a + b;
};
a and b are the function’s parameters, and the value it returns is signified by the return keyword. The return keyword also stops execution of the code in the function; nothing after it will be run.


var result = add(1, 2); // result is now 3
This calls add with the arguments 1 and 2, which, inside add, will be saved in the variables a and b.

No comments:

Post a Comment