Introduction
A function is like a machine that we use daily to simplify our lives, such as a cloth-washing machine, an electric bulb, and other similar things. For instance, a cloth-washing machine helps us clean tons of clothes in a short amount of time effectively. It performs a specific task (like washing clothes quickly and effectively), and this is analogous to a function in programming. Hopefully, this real-life example clarifies, the concept of a function.
Function in JavaScript
JavaScript is a programming language. We use functions in every programming language to enable functionality on our website or application. A function is a block of code written for a specific task. In JavaScript, we write functions to add specific functionalities. A JavaScript function is written as shown below:
function sumTwoNumbers(a, b) {
return a + b;
}
console.log(sumTwoNumbers(3, 5));
// Output: 8
Let’s break down this function:
This is how a formal function is written in JavaScript. This is the structure of our function that we must follow:
- function is a mandatory keyword; we can’t change these words. It is used to create a function.
- sumTwoNumbers is the name of the function. We can use any name here, and it is used to invoke the function to get a value.
- (a, b) are the parameters. We can use any name instead of a and b. These are used to add values as input.
- return is a keyword that is used to return the final value of the function.
There are many types of functions in JavaScript. One of the simplest is known as Function Declarations, which we have studied above. I am not going to cover each and every function in this article; however, I will show you other functions that are frequently used in JavaScript after this function. Understanding these functions is essential.
Function Expressions
This function works similarly to Function Declarations. In this type of function, we provide a name before the function keyword, and the rest is written similarly to Function Declarations. In this case, we call the function by its name, as shown in the example below:
const greet = function() {
console.log('Hello, world!');
}
greet();
// Output: Hello, world!
Arrow Function
const greet = () => {
console.log('Hello, world!');
};
greet();
// Output: Hello, world!
This is an Arrow Function. In this function, we don’t need to use the function keyword; instead, we start with the arrow =>. This function also works the same way as Function Declarations. this function can also be used as an inline function, for example:
const greet = () => console.log('Hello, World!');
greet(); // Output: Hello, World!