Functions
It is considered a special built-in object type, which contains a block of code designed to perform a particular task. It is intended for a reusable set of instructions that can be named and called whenever needed.
A function is defined with the keyword
functionfollowed by a name, the()characters, and a block with the instructions to store is surrounded by the{}characters. Then, to call it, we use its name and the()characters.
function test(){ // Declaration of a function
console.log(1+2);
};
// We can assign a function with no name to a variable
test = function(){ // This is known as an anonymous function
console.log(1+2);
};
test = function(){ console.log(1+2); }; // Can also be declared in a single line
test() // This calls the function and executes its content, prints 3We can even call a function before its declaration. JavaScript will search the function in the current block, then through the imported modules and global variables, and then through the built-in functions
test2() // Called before declaration, prints 4
function test2(){ // Declaration of a function after its call
console.log(2+2);
};Functions can also receive external variables or variables to use. These are known as parameters of the function. The variables name that are passed to a function don't need to have the same name as the parameters used in the declaration. They are passed as a representation to simplify the logic, no matter which values or variables are used
Default values can be set for parameters in case they do not receive a value to avoid errors or simplify operations
We can also define variables inside functions, but this will remain in the scope of the function, and after execution, they will be deleted
We can also use the
returnkeyword to send values back when the instructions are completed. This allows us to send variables, operation results, objects, and even other functions. If a function doesn´t print or return anything, it's set toundefinedby default
The
returnkeyword ends the execution function, so when we hit areturn, the value is sent back, and the next instructions are not executed
We can also use functions inside other functions. The functions used inside are called Helper Functions and are usually designed to do simple operations
Functions are considered objects in JS, and when they are assigned to variables, they are passed as references to those objects. With this, we can access the attributes and methods they have
Arrow Functions
It is a shorter way to write functions and set them to variables. With them, we can quickly define the attributes, then use an arrow represented as => and the instructions to be done and returned. For example:
This allows us to use functions as variables, pass them as arguments to other functions, or return them from functions. These functions being invoked are called Callbacks, and the functions that call another are called Higher-Order functions. For example:
Last updated