javascript-que-son-las-funciones

What are and how to use functions in JavaScript

  • 2 min

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

Functions are a fundamental part of programming, as they allow dividing code into smaller, more manageable units. This facilitates understanding, maintaining, and debugging software.

If you want to learn more, check out the Introduction to Programming Course

Function Declaration

Functions can be declared in several ways in JavaScript. The most common way is 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
}
Copied!
  • functionName is the name we give to the function,
  • parameter1, parameter2, etc., are the parameters the function can receive.

Parameters are optional, meaning a function can receive no parameters or can receive several.

Basic Example

An example of a function declaration would be:

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

In this case, the greet function receives a name parameter 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 to it in parentheses.

Following the previous example, to call the greet function with the name “Luis”, you would do it as follows:

greet("Luis");
Copied!

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

Anonymous Functions

Anonymous functions are those that have no name and are declared inline. They are commonly used as arguments for other functions or to declare a function inside another.

The syntax for an anonymous function is as follows:

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

An example of an anonymous function could be:

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

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