A JavaScript function is a block of code designed to perform a particular task. Sometimes a function return a result. If a function do not return a result it may have a side effect and it returns “undefined” value.

Example:

function myFunction(p1, p2) {
    return p1 * p2;              
}

var x = myFunction(5, 5);

Function Invocation

The JavaScruot function can be call using operator () after function name. The function can be located in a <script> or in a file. There are 3 basic ways to call a JavaScript function.

  1. From another function or JavaScript code;
  2. When an event occurs. For example user click a button or a link;
  3. Automatic invocation (self invoked).

Function Result

A function can calculate a value and return value back to the caller. We use “return” keyword. In the example we use an expression to return value of multiplication between arguments. Results can be ignored in JavaScript.

 

Function Parameters

A function can have no parameters or several parameters. The parameters can have initial values. In next example p2 has default value 10.

function myFunction(p1, p2 = 10) { 
return p1 * p2; } 

var x = myFunction(5, 5);
var y = myFunction(5);

console.log(x); //expected 10
console.log(y); //expected 15

 

Functional Programming

JavaScript can be used as a functional programming language. This is very good feature of JavaScript. It may be difficult to understend from the beginning so here are the fundamentat concepts of functional programming.

  1. You can assign a function to a variable;
  2. You can create a function that can have as a result another function;
  3. You can use a function as a parameter to call other function;

Example:

In this example we use higher order function to create a “closure“.

var counter = function counter() {
  var count = 0;
  return {
    getCount: function getCount() {
      return count;
    },
    increment: function increment() {
      count += 1;
    }
  };
};

Note: Maybe this example is difficult to understend if you do not already know functional programming.

  • A closure is a special kind of function that have private variables;
  • A high order function is a function that return other function;
  • A callback function is a function that use other function as argument;

In the example we actually create an object counter that has inside a function getCounter and a function increment. Function counter() is a closure function.

Callback functions

A callback function is a higher-order function. Is a function that is passed to other function as a parameter. The callback function is called inside the other function.