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, in here, we omitted the function name. This then call as an anonymous function. But you can use this with a function name as well.
- 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 how many years do I have to be retired. 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 be retired, which would be 65. Then, produce a result saying that how many more years do I have to be retired.
`
const yearsToRetirement = (birthyear, firstName) => {
const age = 2021 - birthyear;
const retirement = 60 - age;
return `${firstName} will be retired in ${retirement} years!`;
}
const retirement = yearsToRetirement(1986, 'Sumudu');
console.log(retirement);
`
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! π€
Top comments (37)
If you wrote a book about learning javascript as detailed and well explained as the above...you will have a best seller. Javascript books , especially for beginners need to be explained as you have done. Perfect.
Thank you so much for your kind words! Comments like this really boost my motivation! β€οΈ
Regarding function expressions, you've omitted to mention that you can name functions defined in this manner - and in fact it can be a good idea to do so. If they are not named they will show up as 'anonymous' functions in stack traces. So, it is equally valid to write:
In this case, stack traces involving the function will show the name
calculateAge
instead of 'anonymous function'I don't disagree with your premise in the least - I prefer explicitly named functions as well.
However introduced with ES2015:
Thank you so much for correcting that, Jon! I will add that part.
Just wanted to show the difference as basics without confusing the newbies, because I was not touching other function types in this article. π
Does the Arrow Function way really work in this case? I copied and pasted the code to run and set the birthyear to 2020, it still says 'eligible'.
I noticed there is a 'eligibleToDrive' and also a 'EligibleToDrive'. Only the first letter is different, but never seen where to use 'EligibleToDrive'.
Hi Raymond, sorry for the confusion and there was an error. And thank you for pointing it out. And I corrected it and added a new code.
Sumudu. It works now. Thank you for the correction.
I've actually read quite a few articles about JavaScript functions, but I must say that this one is by far the best at explaining them. Now I feel like I have a much better understanding of functions. Thank u so much
I just wanted to say thank you so much for writing this article because I have so much better understanding of functions than I did now. Thank you so much for breaking this down.
I had so much trouble in understanding how they worked but this actually clicked for me. Please keep writing these.
Me lo leΓ todo π buen aporte!! Thanks
Great read. Loved every word of itπ―π§‘
Thank you, Shubhra!
OMG! I did that, and it worked! Thank you so much!!!!
Nice and Amazing Post. You should also start a newsletter :-D
Keep it up I like this Dua to make man love you and have eyes on you