Functions

Functions are one of the fundamental building blocks in JavaScript. They’re essentially a block of code designed to perform a particular task, and which is executed when "something" invokes it (calls it). They allow the code to be called many times without repetition.

The Function’s syntax:

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses () that may include parameter names separated by commas, followed by JavaScript statements that define the function, enclosed in curly brackets { /* … */ }. Like so:

function name(parameter1, parameter2, parameter3) {
  // code to be executed
}

For example:

// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
  return p1 * p2;
}

General notes regarding functions:

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

A function can be invoked (called) when an event occurs (for example when a user clicks a button), when it is invoked (called) from JavaScript code or can be automatically invoked (self-invoked).

Calling and executing a function:

Defining a function does not execute it. It only gives it a name and specifies what to do when the function is called.

So calling the function is what actually performs the specified actions with the indicated parameters, and not defining it.

You can call a function simply by typing it’s name, and specifying its parameters (if it has any). Like so:

// Defining the function
function myFunction(p1, p2) {
  return p1 * p2;
}
// Calling (executing) the function with the parameters 2 and 3
myFunction(2,3); // which in this case will return 6

You can also call a function a put its results directly into a variable, like so:

let x = myFunction(4, 3);

Note: Something that you need to be aware of, but we won’t be diving too deep into in this section, is the fact that a function can also call itself, which we call *recursivity. Like in the following example:

function factorial(n) {
  if (n === 0 || n === 1) {
    return 1;
  } else {
    return n * factorial(n - 1);
  }
}

In JavaScript, you can use a function before declaring it, which is a feature called hoisting. It is a mechanism that the JavaScript engine does by physically moving function declarations to the top of the code before executing them. For example:

// ----- If you write your code this way, it's perfectly executable -----
showMe(); 

function showMe(){
    console.log('a hoisting example');
}

// ---- Because with hoisting, the code actually becomes like this before execution:
function showMe(){
    console.log('a hoisting example');
}

showMe(); 

Function Examples:

Here are a couple of function examples for you to go through to better understand how functions are written in JavaScript:

  • Function to return a message:
function say(message) {
    console.log(message);
}

let result = say('Hello');
console.log('Result:', result);
  • Function to return the sum of 2 numbers:
function add(a, b) {
    return a + b;
}
let sum = add(10, 20);
console.log('Sum:', sum);
  • Function to compare 2 values:
function compare(a, b) {
    if (a > b) {
        return -1;
    } else if (a < b) {
        return 1;
    }
    return 0;
}

And here’s a quick video about functions that you can watch:

Debugging your code:

Programming code might contain syntax errors, or logical errors, which can sometimes be difficult to diagnose because, often, when programming code contains errors, nothing will happen. There are no error messages, and you will get no indications where to search for errors.

So searching for (and fixing) errors in programming code can be very important. This process is called code debugging.

Debugging is not easy. But fortunately, all modern browsers have a built-in JavaScript debugger that can be turned on and off, forcing errors to be reported to the user.

Normally, you activate debugging in your browser with the F12 key, and select "Console" in the debugger menu.

There are a couple of ways with which you can debug your code. You can do so by using:

  • The console.log() method
  • The debugger Keyword
  • Breakpoints

The console.log() Method:

You can use the console.log() method to display JavaScript values in the debugger window, like so:

a = 5;
b = 6;
c = a + b;
// If you want to see the value of c:
console.log(c);

The debugger Keyword:

The debugger keyword stops the execution of JavaScript, and calls the debugging function which will stop executing the code at that specific breakpoint before it executes the next line.

For example:

let x = 15 * 5;
debugger; // stops the execution
console.log(x);

If no debugging is available, the debugger statement has no effect.

Using Breakpoints:

Using the debugger window, you can set breakpoints in the JavaScript code. This will stop executing at each breakpoint, and let you examine JavaScript values, and then resume the execution of code (typically with a play button).

You can read more about debugging through this link.