Functions

In this section, we delve into JavaScript functions, one of the most powerful and fundamental aspects of the language. Functions in JavaScript are used to encapsulate reusable code, making your programs more modular, efficient, and manageable. They are the building blocks that allow you to execute specific tasks and manipulate data in a variety of ways.

Desired Outcomes:

  • Grasp the fundamental concept of functions in JavaScript and their role in structuring and organizing code.
  • Learn how to pass parameters to functions
  • Learn different ways to define functions, including function declarations and expressions.
  • Understand the difference between parameters and arguments, and how to effectively pass data to functions.
  • Learn how functions return values and how these values can be used in your program.

A JavaScript function is a block of code designed to perform a specific task. Functions in JavaScript are executed when they are called or invoked.

function multiplication(x, y) {
    return x * y; // The function returns the product of the passed numbers
}

A JavaScript function is defined with the keyword function, followed by the name of the function, and then followed by open and closed parentheses: (). Function names follow the same rules as variable names.

Parameters can be passed into the parentheses, separated by commas (parameter1, parameter2, parameterN). The parameters of a function are the names listed in the function definition, and they act as local variables within the function itself.

The code that the function executes is written inside curly braces {} as shown in the following example.

function functionName(parameter1, parameter2, parameterN) {
    // Code
}

Calling a Function

As previously mentioned, for a JavaScript function to be executed, "something" has to call it. Functions can be called:

  • When a predetermined event occurs (e.g. a mouse click on a certain element)
  • By calling the function within JavaScript code
  • Automatically (they call themselves)

To call a JavaScript function, you need to specify the function name, parentheses (), and pass any parameters into the parentheses if the function defines them.

functionName(parameter1, parameter2, parameterN);

If we wanted to call the multiplication function from the previous example, the implementation would look like the following code:

// Function definition
function multiplication(x, y) {
    return x * y; // The function returns the product of the passed numbers
}

// Calling the function
multiplication(5, 4); // The result is 20

Function Return (return)

When the JavaScript interpreter reaches a return statement, the function will stop executing. If another function is specified in the return statement, JavaScript will "return" to execute the code within the called function.

Functions most often return some calculated value, and the return value is returned to the function caller. For example, in the code below, a variable called sum is declared, and a function called sumNumbers is created that takes two parameters and performs the mathematical operation of adding those parameters.

var sum = sumNumbers(2, 5); // 7

function sumNumbers(a, b) {
    return a + b;
}

In the sum variable, the sum of the two given numbers is returned.

The advantage of using functions is that you do not need to write the same code multiple times to execute the same functionality. A function is defined once and can be called as many times as needed. In this way, it is possible to execute the same code multiple times with different arguments to produce different results.

As previously mentioned, it is also possible to use functions as variables in JavaScript. In the example below, the result of the function is concatenated within the text variable.

var text1 = "The sum of numbers 5 and 2 is: " + sumNumbers(5, 2);
var sum = sumNumbers(5, 2);
var text2 = "The sum of numbers 5 and 2 is: " + sum;

Scope and Closure

Scope refers to where variables and functions are accessible within your code.

A closure is a function that remembers the variables from the place where it is defined, regardless of where it is executed later.

function outerFunction() {
    let outerVariable = 'I am outside!';
    function innerFunction() {
        console.log(outerVariable);  // Accessing outerVariable
    }
    return innerFunction;
}

let inner = outerFunction();
inner();  // Outputs: 'I am outside!'

In the above example, innerFunction is a closure that accesses outerVariable, a variable in its outer scope. Even after outerFunction has finished execution, innerFunction remembers outerVariable.

Arrow Functions

Arrow functions, introduced in ES6 (ECMAScript 2015), provide a more concise syntax for writing function expressions. They are particularly useful for short, single-operation functions and have some differences in behavior compared to traditional function expressions.

Syntax of Arrow Functions:

An arrow function expression has a shorter syntax compared to function expressions and does not have its own this, arguments, super, or new.target. 

The basic syntax is:

(parameters) => { statements }

If the function has only one parameter, the parentheses can be omitted. If it contains a single expression, the curly braces and the return statement can be omitted as well.

Examples of Arrow Functions:

Single parameter without parentheses:
const square = x => x * x;
console.log(square(5)); // Output: 25

Multiple parameters:

const add = (a, b) => a + b;
console.log(add(3, 4)); // Output: 7

Function with multiple statements:

const divide = (a, b) => {
    if (b === 0) {
        return 'Cannot divide by zero';
    }
    return a / b;
};

console.log(divide(10, 2)); // Output: 5    

In conclusion, arrow functions provide a more concise syntax and address some common pitfalls associated with traditional functions, especially around the this keyword. They are best suited for non-method functions and cannot be used in all situations where traditional functions are used.

Updated on:

Part of our complete: JavaScript Fundamentals guide

Want exercises and real projects for this lesson? Get the full course.