JavaScript: Functions

Notes Home

At the most basic a function is a block of code. Functions in JavaScript can be very complex because functions are objects which can be passed and manipulated like variables. Functions can be written inside of other functions. Essentially, functions are blocks of code, assigned to a name like a variable. That code can take inputs and create outputs and perform other operations. It can be modified and used multiple times.

function printName(name) {
  console.log(name);
}
printName("Jerry");

Functions are named like variables but have parenthesis to distinguish them as functions and to contain arguments.

Functions, objects and methods

The examples we'll look at today are going to use all of these concepts. We'll cover them in more depth this semester, but let's define them quickly so we know what we're talking about:

Functions have to be called in order to be executed. This can be done with a call to the function as seen above. Functions can also be made to self instantiate by adding a () to the end of the declaration, which are referred to as Immediately Invoked Function Expressions.

(function printName() {
  console.log("Hello, Jerry");
})();

The paranthesis wrap the function to tell the browser it is one statment.

Functions take arguments, as in the above example, where "Jerry" is the argument. This can be replaced with any string in the function call. We can declare the number of arguments in the function declaration, or we can put in whatever arguments we want in the call and use the arguments variable to manipulate them. If you add more arguments to the add() function, it will not throw an error, but it will ignore the arguments beyond the first two.

function add(n1, n2) {
  console.log(n1 + n2);
}
add(5, 6);

function printArgument() {
  console.log(arguments);
}
addMore(5,6,7,1,6);

Functions can also return values. This is useful for evaluating expressions and assigning variables.

function add(n1, n2){
  return n1 + n2;
}
x = add(5, 25);

Functions can also be declared as anonymous functions, which uses an expression syntax, such as var add = function(n1, n2){ .... }. It has the same functionality as the function add() { .... } format, but can be written in different places in code.

Resources