1.13 Defining Functions

Generaly, we can hide the details of any computation by defining a function. For exemple, earlier we use the Math.sqrt() function that act as a blackblox. You give it a number and it returns its square root. A function definition requires a name, a group of parameters, and a body. It may optionally return an output. A function in JavaScript is also an object. For example, the simple function defined below returns the square of the value you pass into it:

function square (n) {
    return n**2
}

console.log( square(3) ); // 9

Because our function has a name, we call it a named function. At the opposite an anonymous function is a function without a function name:

function () {}

A function inside another function is an inner function (square in the exemple below). So an outer function is a function containing a function (addSquares in this case):

function addSquares(a,b) {
   function square(n) {
      return n**2;
   }
   return square(a) + square(b);
}

A recursive function is a function that calls itself:

function loop(x) {
   if (x >= 10)
      return;
   loop(x + 1);
}

We can also define an Immediately Invoked Function Expressions (IIFE). This kind of function is called directly after being loaded into the browser’s compiler.

We could implement our own square root function by using a well-known technique called "Newton's Method". Newton's Method for approximating square roots performs an iterative computation that converges on the correct value. The equation newguess = 1/2 ∗ (oldguess + n/oldguess) takes a value n and repeatedly guesses the square root by making each newguess the oldguess in the subsequent iteration. The initial guess used here is n/2. The function below shows a definition that accepts a value n and returns the square root of n after making 20 guesses. Again, the details of Newton's Method are hidden inside the function definition and the user does not have to know anything about the implementation to use the function for its intended purpose. It also shows the use of the // characters as a comment marker. Any characters that follow the // on a line are ignored.

function squareroot (n) {
    root = n/2; // Initial guess will be 1/2 of n
    for (var i = 0; i < 20; i++) {
        root = (1/2) * (root + (n / root));
    }

    return root;
}

console.log( squareroot(9) ); // 3
console.log( squareroot(4563) ); // 67.54998149518622

results matching ""

    No results matching ""