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 break the code into smaller, manageable units. This makes it easier to understand, maintain, and debug the software.

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 parameter name and simply prints a greeting message to the console.

Calling Functions

Once a function has been declared, it can be called at any time using its name, followed by the parameters you want to pass 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 inline. 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 the sum of both.