What is Function and how many types of functions are there in JavaScript?

Photo by Luca Bravo on Unsplash

What is Function and how many types of functions are there in JavaScript?

The function is a simple piece of code that can be used again and again it looks like a variable but is actually a piece of code.

There are 3 types of function

  1. Function declaration.
  2. Function expression.
  3. Arrow function.

1. Let's have a look at Function declaration

How to write it?

Screen Shot 2022-10-30 at 3.18.14 pm.png

A function declaration is simply declaring the function with a name and if you want to pass a parameter inside you can use it inside brackets.

Screen Shot 2022-10-30 at 3.25.39 pm.png

Note: Function declaration can be called even before creating it. Meaning you can call the function name first and then you can create a function with the same name. This is because of Hoisting

Screen Shot 2022-10-30 at 3.27.03 pm.png

2. Let's have a look at Function expression

It is simply a function that can be written as an expression.

How to write it?

Screen Shot 2022-10-30 at 3.34.08 pm.png

Again here it's similar if you want to pass a parameter you simply pass inside the bracket same as the function declaration. you simply can use the return keyword to return the output.
Note: The only difference between function declaration and expression is this function cannot be called before declaring it because hoisting is not applied to this. It is a good practice to use function expression to avoid bugs and errors because you need to declare all the functions before assigning the value

3. Let's have a look at the Arrow function

The arrow function is simply the shorter form of the function made in ES6 to write it easily. How to write?

Screen Shot 2022-10-30 at 3.57.50 pm.png Note: In the arrow function If the argument is 1 liner then you don't have to use the return keyword but if the arguments inside the body are more than 1 line then use the return keyboard to return the value.

Important: All function have their own use a declaration can be declared even before it is actually created while a function expression can only be called once it is created and an arrow function also cannot be called before it is created.