Define a Function in JavaScript
Functions in JavaScript are custom code written by programmers that are reusable and can prevent you from writing the same code again and again. All it needs is just call the function that is defined to use in the program. It is very useful as it increases the code reusability as well as makes the program compact.
In this article, I will show you different ways to Define a Function in JavaScript. So stay tuned through this article…
Different ways of creating a JavaScript function
There are multiple ways available to create functions in JavaScript. But here in this tutorial, we are going to see two ways of creating it. Both ways we are going to show you are quite easy.
Define our function
Below is the most popular way of defining a JavaScript function:
// Defining the function function function cspdFunction() { // Your code will be here }
Now below is the function with code inside it and also shown how we can call the function:
// Defining the function function cspdFunction() { console.log("Welcome to CodeSpeedy"); } // Call the function cspdFunction()
The above code will show “Welcome to CodeSpeedy” in the console as we are calling the function.
Function with parameters
Now below is the function with a parameter:
// Defining the function function cspdFunction(num1, num2) { var sum = num1 + num2; return sum; } // Call the function cspdFunction(3,2) // It will return 5
The above function will ad two numbers that we will pass as parameters. When we call it with parameters, it will return the sum of the numbers that we will pass as the parameters.
Also, read: Calling a JavaScript function on form submit
Creating an Arrow Function
Now it’s time to see another amazing way of creating a function in JavaScript. Let’s look at the code given below:
// Creating the function const sumNum = (a, b) => { return a + b; } // Call the function sumNum(10, 7); // Return the sum as 17
The way we choose to create the above function is called the arrow function in JavaScript which is the simplest way to define a function. This is a new technique of defining a function where you can see that we don’t have to use the JavaScript function keyword.
I hope, now you have a clear idea about the functions and how to use them in the program.
Leave a Reply