Language: EN

javascript-que-son-las-funciones

What are and how to use functions in JavaScript

Functions are blocks of code that can be defined once and then called multiple times at any time.

Functions are a fundamental part of programming, as they allow you to divide the code into smaller, more manageable units. This facilitates the understanding, maintenance, and debugging of the software.

If you want to learn more about Functions
check out the Introduction to Programming Course read more

Function Declaration

Functions can be declared in several ways in JavaScript. The most common way is the function declaration, which is done using the function keyword.

The syntax for a function declaration is as follows:

function functionName(parameter1, parameter2, ...) {
  // Code to execute
}

Where functionName is the name we give to the function, and parameter1, parameter2, etc., are the parameters that the function can receive. Parameters are optional, meaning a function may not receive any parameters or may receive several.

Basic Example

An example of a function declaration would be:

function greet(name) {
  console.log("Hello " + name + "!");
}

In this case, the greet function receives a name parameter and simply prints a greeting message to the console.

Function Call

Once a function has been declared, it can be called at any time using its name, followed by the parameters to be passed in parentheses.

Continuing with the previous example, to call the greet function with the name “Luis”, it would be done as follows:

greet("Luis");

This would print the message “Hello Luis!” to the console.

Anonymous Functions

Anonymous functions are those that do not have a name and are declared in line. They are commonly used as arguments for other functions or to declare a function within another.

The syntax for an anonymous function is as follows:

let functionName = function(parameter1, parameter2, ...) {
  // Code to execute
}

An example of an anonymous function could be:

let add = function(a, b) {
  return a + b;
}

In this case, the add function receives two parameters a and b, and returns their sum.