My first introduction to functions was a doozy... When I was learning how to code, it was all done within a main function. That made sense to me, the code was written in the exact order that it was performed in. Next thing I know, they're throwing functions at me and telling me it will be helpful. It was not until the second time going over functions when I realized how helpful they really are!
The two different segments of code below have the same outputs; however, the second, through functions, is shorter and much easier to understand.
console.log("Math:" );
let a = 1 + 2;
console.log(`1 + 2 = ${a}`);
a = 2 + 2;
console.log(`2 + 2 = ${a}`);
a = 3 + 2;
console.log(`3 + 2 = ${a}`);
a = 1 * 2;
console.log(`1 * 2 = ${a}`);
a = 2 * 2;
console.log(`2 * 2 = ${a}`);
a = 3 * 2;
console.log(`3 * 2 = ${a}`);
a = 1 - 2;
console.log(`1 - 2 = ${a}`);
a = 2 - 2;
console.log(`2 - 2 = ${a}`);
a = 3 - 2;
console.log(`3 - 2 = ${a}`);
a = 1 / 2;
console.log(`1 / 2 = ${a}`);
a = 2 / 2;
console.log(`2 / 2 = ${a}`);
a = 3 / 2;
console.log(`3 * 2 = ${a}`);
The code above is long and extremely repetitive, functions can provide clarity and minimize redundancy, as seen below.
function add(a, b){
return `${a} + ${b} = ${a + b}`;
}
function subtract(a, b) {
return `${a} - ${b} = ${a - b}`;
}
function multiply (a, b) {
return `${a} * ${b} = ${a * b}`;
}
function divide (a, b) {
return `${a} / ${b} = ${a / b}`;
}
console.log("Math:");
console.log(add(1,2));
console.log(add(2,2));
console.log(add(3,2));
console.log(multiply(1,2));
console.log(multiply(2,2));
console.log(multiply(3,2));
console.log(subtract(1,2));
console.log(subtract(2,2));
console.log(subtract(3,2));
console.log(divide(1,2));
console.log(divide(2,2));
console.log(divide(3,2));
This code, consisting of four functions, allows my main code to be shortened, and due to proper function naming, easy to read. This code could be shortened even more using loops (which I will discuss in another post).
Let's break this code down
We will start by diving into our add function.
function add(a, b){
return `${a} + ${b} = ${a + b}`;
}
As seen above, there are a few things that are included in this function.
There is a function keyword. The function keyword tells javascript that you are creating a function. This is important; however, function keywords are not necessary, which I will explain later.
A clear function name is provided to allow others to understand what your function is supposed to do. Others looking at your code should know what the function does just from its name.
Parameters are the variables found within the (). By including parameters, you can pass values to the function, which is what help make functions such a powerful tool.
Curly braces! These are important for the function in the example above; however, I will show examples below where curly braces are not required.
Return keyword. This keyword is also not always required, but for this example, without it, your functions would return 'undefined'. This is because the function has to return something and if you're not giving it anything to return, it will think that you want it to return nothing.
The return keyword is useful if you want to take the output of a function and use it again later. For example:
function add(a, b){
return a + b;
}
function divide(a, b){
return a / b;
}
const addedNum = add(2,4);
const dividedNum = divide(addedNum, 2);
By using the return keyword in my add function, I was able to assign the output to a variable and use it in another function.
Let's now talk about calling the function
add(1,2)
To call the function is quite simple, all you need is the function name, and the parameter values you want to pass into the function.
Different ways to define functions
There are three ways to to write a function in javascript.
1. Function declaration
Function declaration is what was being used above.
This way of defining a function is useful because it allows you to invoke the function before it is defined, otherwise known as hoisting.
add(2,4)
function add(a, b){
return a + b;
}
Even though I am calling the function before I have declared it, the add call will still execute.
2. Function expressions
This is defining a function by using a variable.
const multiply = function (a, b){
return a * b;
}
This example shows the same multiply function, but it is defined using function expression.
3. Arrow Functions
Arrow function notation is great for making your code concise.
const multiply = (a, b) => a * b;
This may be a little difficult to read at first, at least it was for me, but let me break it down.
The arrow notation can be defined using a variable, similar to function expression. However, it skips over all the additional keywords and allows you to write your function definition in one line. The parameters are entered in after the "=" and the arrow points to what will be returned.
As you can see, no return key word is required when using arrow function notation, otherwise known as implicit return.
Curly braces are not required when only one line of code is necessary; however, if more lines are required, the curly braces are needed to enclose everything after the arrow.
const greetings = (userName, helloGreeting, goodbyeGreeting) => {
console.log(`${helloGreeting}, ${userName}, it is nice to meet you!`);
console.log(`${goodbyeGreeting}, ${userName}`);
}
As you can see, I had to use curly braces because my return code was longer than two lines.
Callback Functions
The last concept that I wanted to touch on was one of the hardest things for me to understand. I did a lot of research to try and figure out how callback functions worked, but ultimately it came down to me utilizing callback functions in my code that made me understand.
A callback function is a function that is being called within another function, this could be an anonymous function, or a function that you had previously defined. It is called a callback function because the function is not executed right away, it is called back to be used at a later time. Let me show you some examples!
const greeting = (userName, callbackFunction) => {
console.log(`Hello, ${userName}, it is nice to meet you!`);
callbackFunction();
}
Here you can see I did an arrow notation function called greeting (similar to the previous example). This greeting function takes a callback function as a parameter, and executes it when it is later invoked at the end of the greeting function.
function iAmCallback() {
console.log(`This is the callback Function`);
}
This is the callback function definition. When used as the callback parameter, calling the greeting function will output "This is the callback Function".
greeting("samuel", iAmCallback);
Lastly, this is how I call the greeting function. I pass it the name, and then the function I want to callback to be invoked when the greeting function is executed. When calling a function and passing in a callback function, it is important to remember to not immediately invoke your callback function by adding () after putting the callback function in as a parameter.
Output:
Hello, samuel, it is nice to meet you!
This is the callback Function
Now using a callback function in this manner is useful when the callback function needs to be invoked multiple times. If the callback function is only used once, you can do an anonymous callback.
const myArray = ["item1", "item2", "item3"];
myArray.forEach(() => {
console.log('This is the anonymous callback Function');
})
In this example, I created an array and iterated through it using the forEach method. For each of the items in the array, the anonymous callback function is performed. The anonymous function is written using arrow notation, taking in no parameters but simply returning the output shown below.
Output:
This is the callback anonymous Function
This is the callback anonymous Function
This is the callback anonymous Function
The function was called three times!
Top comments (0)