This content originally appeared on DEV Community and was authored by Sumudu Siriwardana
If you are a newbie to programming and JavaScript, you might first find it hard to grasp the concept of functions.
When I first learned about functions, I thought I got it all right. Then, when I tried to apply it in some code challenges, I got more confused, and I had to go back and forth reading my notes to understand functions more deeply.
I came to the point that I doubted myself and felt like I was not up for this. But without giving up, I started digging deeper into functions and finally understood them.
So this post is for newbies like me, who are trying to understand this concept in a simple form!
Let's get going! ?
Check out the Table of Content below to see what we will be going over in this post.
Table of Content
- What is a function
- Parameters and Arguments
- Return Statement
- Calling a Function
- Function Declarations
- Function Expressions
- Arrow Functions
What is a function
A function is the fundamental building block of a JavaScript application. It is one of the most essential concepts in the language.
Let's take a simple machine. What does it do? It takes an input, processes it inside, and gives an output.
For example, think about this coffee machine below. It takes ground coffee, brews it, and makes a great cup of black coffee.
That's exactly what functions do as well! ?
We pass data into a function, and we process that data inside the function or do something with that data inside a function, and then we output or return that data.
The most simple form of a function is a simple piece of code that we can repeatedly reuse in our code. What does this mean?
With function, you don't have to write that code over and over again throughout your program. Instead, once you create a function, you can reuse it whenever you want. Confused? Let's come back to it later.
Now let's create a simple function.
function myName() {
console.log('My name is Sumudu');
}
myName();
So what have we done here?
- We started with the
function
keyword. This is how we declare a function. - Then, we defined a function name, which is
myName
. This is the given name for the function, which is a function that will simply log something to the console. - Then, we added
parenthesis
. We useparenthesis
to add parameters, which we will be exploring more later in this post. - Then, we used
curly braces
to create a function body. All the code that is within thiscurly braces
is called the function body. And it's this code that will be executed when we run this function. - To use this function, we simply write the function name followed by a
parenthesis
. And this process is called "invoking", "running", or "calling" the function.
So this is the simple way of writing a JavaScript function and the syntax of it! ?
Now you might be thinking that we are writing more code with functions. That's true!
But the beauty of it is that we can use this function again and again throughout our program when we need it. So we don't have to duplicate the code. Let's look at a simple example to understand this.
Let's say you want to add ten to a number. Here's how we can do it without functions.
const number = 1 + 10;
// Answer = 11
Now let's write this using a function.
function addTen(number) {
return number + 10;
}
const firstNumber = addTen(1); // Answer = 11
As you can see, we have written more code in the second example, but it would be useful to write a cleaner code when we want to add ten to more numbers. Check the below example.
function addTen(number) {
return number + 10;
}
const firstNumber = addTen(1); // Answer = 11
const secondNumber = addTen(2); // Answer = 12
const thirdNumber = addTen(3); // Answer = 13
const fourthNumber = addTen(4); // Answer = 14
const fifthNumber = addTen(5); // Answer = 15
I hope now you can understand how we can write something once and reuse it again with functions. Functions help us reduce, reuse, and recycle our code, which is something awesome! ?
Now let's move on to understand few other parts of functions. Which are;
- Parameters and Arguments
- Return Statement
- Calling a Function
Parameters and Arguments
This is something I really got confused with when I was learning about functions. I couldn't remember the difference properly and was wondering why my function was not working properly ?
Let's check the below picture.
As you can see, we added the function parameter inside the parenthesis. This is the input or list of input values that need to be received to perform the function. You can think of it as an empty placeholder that needs to be replaced later on.
Arguments are actual values of function parameters for those input data. So in the above examples, the placeholder is replaced by the actual data, the number "1".
Return Statement
With the return
keyword, we can return any value from the function. Some functions may not return a value, but most functions do. We call this value the result of the function. Then, this value that is returned can be used anywhere later in the code.
Let's look at an example.
function addTen(number) {
console.log(number + 10);
}
addTen(1); // Answer = 11
function addTwenty(number) {
return number + 20;
}
const firstNumber = addTwenty(1); // Answer = 21
In the first function, we haven't returned a value; we have simply logged a value inside the function. And then, we called the function and got the logged value as "11".
In the second function, we have returned a value as a result of the function. And then, we have stored the function in another variable (firstNumber
) and called the function. So every time the function is called, the returned value will be the result of the function.
One important thing that you have to keep in mind is that this return
keyword immediately exits the function. It first returns the value that we ask it to return, in this case, the number + 20
. After that, the function is DONE!
It doesn't execute any other code after the return
keyword. So, for example, in the below code, you can see that there's a console.log
after the return
. But if you run this code, you can see that code stops right after the return
and doesn't run the console.log
.
function addTen(number) {
return number + 10;
console.log("Let's add numbers!")
}
const firstNumber = addTen(1); // Answer = 11
So if you want to run the console.log
, you have to place it before the return
keyword.
Calling a Function
Let's say that you have written a function. So how do we use this function?
To use a function, we simply write the function name followed by a parenthesis
. And this process is called "invoking", "running", or "calling" the function.
If you remember the first example, to log the name using the function we created, we used the function name followed by the parenthesis
below the function that we have written (outside of the function).
function myName(){
console.log('My name is Sumudu');
}
myName();
If you want to store the values that are returning from the functions and use them later on, you can always store it in another variable by creating another variable and adding the function name as the value of that variable.
Let's look at the below example to understand how to do that.
function addTen(number) {
return number + 10;
}
const firstNumber = addTen(1); // Answer = 11
In the above example,
- We have created a variable called
firstNumber
. - We have given the function name (
addTen
) as the value to that variable.
Now you can use this variable to call the function whenever you want! ?
Alright! Now you have learned the basic parts of a function. So let's look at the below pictures to recap everything and understand the anatomy of a function!
I hope now you have a basic idea of how the function works and the basic parts of Javascript functions.
There are different ways to write JavaScript functions. We will be looking at three ways of writing functions in the next few sections. These three types are:
- Function Declarations
- Function Expressions
- Arrow Function
Are you ready? Let's go!
Function Declarations
We use the function
keyword to declare a function. Same like we declare a variable ?
So let's declare another function to calculate the age based on the birth year.
//Function declaration
function calcAge1(birthyear) {
return 2021 - birthyear;
}
const age1 = calcAge1(1986);
Let's see what we have done here,
- We have created a
function
by giving the namecalcAge1
to calculate the age. - And we have given the function parameter as
birthyear
. So that's the input data that we will be taking to calculate the age. - We will be returning the results by subtracting the
birthyear
from the current year to calculate the age. - Then, we stored this
function
in another variable (age1
) and called the function, and we have given the actual data to calculate the age inside thecalcAge1
.
So this is how we simply declare a function. I hope this is clear to you!
Function Expressions
Now let's see how we can perform the same function with the function expression.
//Function expression
const calcAge2 = function(birthyear) {
return 2021 - birthyear;
}
const age2 = calcAge2(1986);
Earlier, we have started with the function
keyword. But with function expression, we write the function as an expression. Remember that an expression produces a value, so we must create a variable to store that value.
- First, we create a variable to store the function (
calcAge2
), which will be the actual function. - Then, we write the function as same as before, but without a function name.
- Next, we add the function parameters, function body, and then call the function.
Yes, simple as that!
Alright! Now you might be wondering what's the big difference or big deal between function declaration and function expression.
There's one major difference between these two. And that is, we can actually call function declaration before it is defined in the code. We call this hoisting.
Function declarations are hoisted, but expressions are not!
In the code below, I've called the function before the function declaration and the function expression. So, if you run this code, cosole.log
will produce an error for the 'calcAge2`. Try it out!
`
//Function declaration
const age1 = calcAge1(1986);
function calcAge1(birthyear) {
return 2021 - birthyear;
}
//Function expression
const age2 = calcAge2(1986);
const calcAge2 = function(birthyear) {
return 2021 - birthyear;
}
console.log(age1, age2);
`
You can learn more about JavaScript hoisting here.
Okay, let's dive into arrow functions!
Arrow Functions
There is another way of declaring functions in modern JavaScript, and that's with the arrow function, which actually looks like an arrow: () => {}
Arrow functions are actually shorter and faster to write. Let's look at the same example that we used before and convert it to an arrow function.
`
//Arrow function
const calcAge3 = birthyear => 2021 - birthyear;
const age3 = calcAge3(1998);
`
Let's see what we have done here,
- We have created a variable (
calcAge3
) to store the function the same as before since the arrow function is also a function expression. - Then, we have added the
birthyear
because we want to calculate the birth year. - Then, we added an arrow (
=>
), and that's the reason we call thisarrow function
. - Then, we simply wrote what we wanted to return (
2021 - birthyear
). - Then, we have called the function the same as earlier.
As you can see, this code is a lot easier and faster to write. And one of the reasons for that is that we don't need the curly braces
like previously to define a code block for the function body. And another reason is that return
actually happens implicitly here; it automatically returns the value without explicitly defining the return
keyword.
So this is actually just the simplest form!
But this form will be changed and gets more complicated when we have more than one parameter or more than one result to return.
Now let's look at a more complex example where we have to use multiple parameters and code.
Let's say that we need to check whether I'm eligible to drive. To do that, I need my birth year and my name as parameters. And then, I want to check my current age and then check it against the eligible age to have a driver's license. Then, produce a result saying that I'm eligible or not.
`
const eligibileToDrive = (birthyear, firstName) => {
const age = 2021 - birthyear;
const EligibleToDrive = age > 18;
return `${firstName} is eligible to drive!`;
}
const eligible = eligibileToDrive(1986, 'Sumudu');
console.log(eligible);
`
So in here, we have wrapped the parameters in parenthesis
and wrapped our code in curly braces
. Same as we have done in function declarations and expressions. That's the only difference that you will see between simple and complex arrow functions.
I hope that now you can understand how you can write simple and complex arrow functions.
To recap and better understand the difference between these three types of functions, refer to the below code.
`
//Function declaration
function calcAge1(birthyear) {
return 2021 - birthyear;
}
//Function expression
const calcAge2 = function(birthyear) {
return 2021 - birthyear;
}
//Arrow function
const calcAge3 = birthyear => 2021 - birthyear;
`
So this is all about the basics of JavaScript functions. Of course, there's a lot more to functions than these basic concepts, but you can easily get through the rest when you understand these basics.
Let's give you all a big hand for reading to the end of this post and trying to understand this complex concept.
I hope this post helps you to clarify all your doubts about functions!
Happy learning! ?
This content originally appeared on DEV Community and was authored by Sumudu Siriwardana
Sumudu Siriwardana | Sciencx (2021-09-27T04:10:14+00:00) JavaScript Functions: Explain Like I’m Five. Retrieved from https://www.scien.cx/2021/09/27/javascript-functions-explain-like-im-five/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.