JAVASCRIPT FUNCTIONS

JS

In the development of complex Web sites and software in general, a key aspect is the organization of the code. Suppose we have an application consisting of ten thousand lines of unstructured code written one after the other. Such a code in the case works would be impossible to manage and maintain, extend and modify. Through javascript functions we can break the code into separate blocks, each of which performs a certain function. These code blocks we can call (invoke) whenever we need them. Functions are defined in such a way that they can receive input data and return output data.

Console
Copy to Clipboard

In this example number_1 and number_2 are the input data, while with the return statement we return the sum variable (output data) that is stored by the sum variable that is outside the code block. The “JavaScript functions” are designed to perform a particular task; they are executed when “something” invokes (calls) them.

function myFunction(p1, p2) {
return p1 + p2; // The function returns the sum of p1 and p2
}

A function is defined by the keyword function, followed by a name, followed by parentheses (). Function names may contain letters, digits, underscores, and dollar signs (same rules as variables). Parentheses can include parameter names separated by commas: (parameter1, parameter2, …). The code to be executed is enclosed in curly brackets: {}

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

The parameters of the function are listed in parentheses () in its definition. The function arguments are the values received by the function when it is called (data passed as input). Within the function, parameters behave as local variables.

INVOCATION OF A FUNCTION

The code within the “javascript functions” will be executed when “something” invokes (calls) the function:

  • When an event occurs (when a user clicks a button)
  • When invoked (called) by JavaScript code
  • Automatically (self-invoked)

You will learn much more about function invocation later.

JAVASCRIPT FUNCTIONS THE RETURN VALUES

When JavaScript reaches an instruction return, the function stops execution. If the function was invoked by an instruction, JavaScript will “return” to execute the line of code immediately after the function call. The “javascript functions” often compute a value, which is “returned” to the “caller.”

let x = myFunction(4, 3); // Function is called, return value will end up in x (7)

function myFunction(a, b) {
return a + b; // Function returns the sum of a and b
}

You can reuse the code: define the code once and use it multiple times. You can use the same code multiple times with different arguments to produce different results.

function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById(“demo”).innerHTML = toCelsius(77);

The operator () calls the function.

Using the previous example, toCelsius refers to the function object and toCelsius() refers to the result of the function. Accessing a function without () will return the function object instead of the result.

function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById(“demo”).innerHTML = toCelsius;

FUNCTIONS USED WITH VARIABLE NAMES

Functions can be used in the same way as variables, in all kinds of formulas, assignments, and calculations.

let x = toCelsius(77);
let text = “The temperature is ” + x + ” Celsius.”

You can use the function directly, as a variable value:

let text = “The temperature is ” + toCelsius(77) + ” Celsius.”

JAVASCRIPT FUNCTIONS LOCAL VARIABLES

Variables declared within a JavaScript function become LOCALS for the function. Local variables can only be accessed from within the function.

// code here can NOT use carName
function myFunction() {
let carName =“Volvo“;
// code here CAN use carName
}
// code here can NOT use carName

Since local variables are recognized only within their functions, variables with the same name can be used in different functions. Local variables are created when a function is invoked and deleted when the function completes.

EXTERNAL VARIABLES

A function can access an external variable, for example:

let userName = ‘John‘;

function showMessage() {

let message = ‘Hello, ‘ +userName;

alert(message);

}

showMessage(); // Hello, John

The function has full access to the external variable. It can also modify it.

Example:

let userName = ‘John‘;

function showMessage() {

userName = “Bob”; // (1) changed the external variable

let message = ‘Hello, ‘ + userName;

alert(message);

}

alert( userName ); // John before function call

showMessage();

alert( userName ); // Bob, the value was changed by the function

The external variable is used only if there is no local one. If a variable with the same name is declared inside a function, it will obscure the outer one. For example, in the code below the function uses the local variable userName. The external one is ignored:

let userName = ‘John‘;

function showMessage() {

let userName = “Bob“; // declare a local variable

let message = ‘Hello, ‘ + userName; // Bob

alert(message);

}

// the function will create is use its own ‘personal’ userName

showMessage();

alert( userName ); // John, untouched, the function cannot access the external variable because it is obscured

GLOBAL VARIABLES

Variables declared outside any function, such as userName in the code above, are called global. Global variables are visible to any function (if they are not obscured by local variables). Usually, a function internally declares all the variables needed to perform its task. Local variables are used to store data related to the function itself. It is good to avoid global variables, although they can sometimes be useful.

DEEPENING AI

In JavaScript, functions are blocks of code designed to perform a specific operation. These are critical to structuring and reusing code efficiently. Here is a detailed description of functions in JavaScript, including their characteristics and types:

1. Declaring a function.

The basic syntax for declaring a function in JavaScript is as follows:

function nameFunction(parameter1, parameter2, …) {
    // Body of the function
    // Actions to be performed
}

-function: This is the keyword that defines a new function.

-nameFunction: This is the name assigned to the function, which should reflect the purpose of the function.

-parameter1, parameter2, …: These are the (optional) parameters that the function can receive as input. They can be used to pass information to the function.

-Function body: Contains the code that is executed when the function is invoked.

2. Calling a function.

Once declared, a function can be invoked (called) in this way:

nameFunction(value1, value2, …);

3. Return value

Functions can return a value using the return keyword. If it is not specified, the function will return undefined.

Example of a function that returns a value:

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

let result = sum(3, 4); // result will be 7

4. Anonymous functions

An anonymous function is a function that has no name. It is usually used as a variable value or passed as an argument to other functions.

Example:

let saluto = function() {
   console.log(“Ciao!“);
};

saluto(); // Invoca la funzione anonima

5. Arrow Functions (Arrow Functions)

Arrow functions are a compact syntax introduced with ES6 (ECMAScript 2015). They have a more concise appearance and do not automatically bind context this like normal functions.

Basic syntax:

(parametro1, parametro2, …) => {
    // Corpo della funzione
    return risultato;
}

const moltiplica = (a, b) => a * b;

let risultato = moltiplica(3, 4); // risultato sarà 12

6. Functions with default parameters

In JavaScript, you can specify default values for the parameters of a function. If a value is not passed at the time of the call, the default value will be used.

Example:

function saluta(nome = “Amico“) {
   console.log(“Ciao, ” + nome);
}

saluta(); // “Ciao, Amico”
saluta(“Giulia“); // “Ciao, Giulia”

7. Functions as arguments (Callbacks)

Functions can be passed as arguments to other functions. This is useful when working with asynchronous functions, such as time-consuming operations (e.g., fetch data or setTimeout).

Example:

function eseguiFunzione(callback) {
      callback();
}

eseguiFunzione(function() {
      console.log(“Funzione eseguita!“);
});

8. Pure functions

Pure functions are those that, given the same input, always return the same output and cause no side effects, such as changing external variables.

Example of a pure function:

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

9. Recursive functions

Recursive functions are functions that call themselves. They are useful for solving problems that can be divided into similar subproblems.

Example of a recursive function that calculates the factorial of a number:

function fattoriale(n) {
    if (n === 0) {
       return 1;
    }
    return n * fattoriale(n – 1);
}

console.log(fattoriale(5)); // 120

10. IIFE (Immediately Invoked Function Expression) Functions.

An IIFE is a function that is defined and invoked immediately.

Example:

(function() {
console.log(“Questa funzione viene eseguita subito!“);
})();

Conclusion

Functions in JavaScript are powerful tools that allow code to be structured in a modular, reusable and maintainable way.

LINKS TO PREVIOUS POSTS

THE JAVASCRIPT LANGUAGE

LINK TO CODE ON GITHUB

GITHUB