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
function
followed 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 3
We 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
test = function(a){ // Declaration of a function with parameters
console.log(a*2);
};
test(4) // We can directly pass values, prints 8
test2 = function(a,b,c){ // Any quantity of parameters can be set
console.log(a+b+c);
};
d=1; e=2; f=3;
test2(d,e,f) // We can pass variables even with different names, prints 6
Default values can be set for parameters in case they do not receive a value to avoid errors or simplify operations
test = function(a=3, b=2){ // Declaration of a function with default parameters
console.log(a*b);
};
test(); // This will use the default values, prints 6
test(2); // This will assign the passed value to the first parameter and use the default for the second parameter, prints 4
test(4,4); // This will use the passed values, prints 16
We can also define variables inside functions, but this will remain in the scope of the function, and after execution, they will be deleted
test = function(a){
let myVar = 3 // Declaration of a variable inside the function
console.log(a/2);
};
test(5) // This prints 2.5
console.log(myVar) // This shows an error, because the variable has been deleted
We can also use the
return
keyword 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 toundefined
by default
sum = function(a,b){
let c = a+b
return c // Returns the value of the variable
};
result = sum(2,5) // This save the result value
console.log(result) // Prints 7
sum2 = function(a){
return a+b // Returns the result of the operation
};
console.log(sum2(2,5)) // This passes directly the result value, prints also 7
undef = function(a){
let value = a // This does not print or return anything
};
console.log(undef()) // This will print undefined
The
return
keyword ends the execution function, so when we hit areturn
, the value is sent back, and the next instructions are not executed
const isFriday = function(day){
if(day === 'Friday'){
return true; // This return is hitted
}
console.log('Wrong'); // This is not executed
};
console.log(isFriday('Friday')) // This will print true
We can also use functions inside other functions. The functions used inside are called Helper Functions and are usually designed to do simple operations
function duplicate(num){
return 2 * num; // This uses the parameter passed from the other function
};
function sumDuplicate(n){
return a + duplicate(n); // This call the first function and uses its result
};
console.log(sumDuplicate(3)) // This will print 9
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
let dupe = function duplicate(num){ // This is passed as reference
return 2 * num;
};
console.log(dupe.name); // Atrribute of the name of the function, prints duplicate
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:
const multiply = (x, y) => { // Define arrow function
return x * y;
};
console.log(multiply(4, 5)); // Prints 20
const sum = (x, y) => x + y; // More compact way using 2 or more parameters
console.log(sum(4, 2)); // Prints 6
const fun = dup => dup * 2; // Using just one parameter
console.log(fun(6)); // Prints 12
const f = () => 2 * 2; // Or even without parameters
console.log(f()); // Prints 4
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:
const higherOrderFunc = param => {
param();
return `Invoked ${param.name} as a callback function`
}
const callBackFunc = () => {
return 'Invoked by a higher-order function';
}
higherOrderFunc(callBackFunc);
Last updated