How to write a function in JavaScript

A function in JavaScript is essentially a segment of code that includes a series of commands designed to accomplish a particular objective. It can be viewed as a reusable code fragment that can be invoked multiple times throughout a program, which helps eliminate the need to duplicate code. Furthermore, it enables developers to break down a large program into multiple smaller, manageable functions.

Types of Functions

In JavaScript, similar to other programming languages such as C, C++, and Java, there exist two categories of functions.

  • Built-in Functions
  • Custom Functions
  • Here we are going to learn, how to write a user-defined function in JavaScript:

In order to define a function in JavaScript, it is essential to begin with the "function" keyword followed by the desired name of the function, as illustrated in the syntax provided:

Syntax of creating function

Example

Function functionname( parameters list)

{



Lines of code to be executed/set of instructions to be executed in order to perform a specific task.

}

Prior to invoking a function in our program, it is essential to establish its definition within the curly braces. Depending on your specific needs, you may choose to leave the parameter list empty, as demonstrated in the syntax provided above.

Example

Example

<script type="text/javascript">  

<!--  

function Hello(){  

alert("Hi, there");  

}  

//-->  

</script>

How to call the function

To invoke the function within our program, we simply need to reference its name, as demonstrated in the example below:

Example

Hello();

Let’s explore a program where we will define a function and subsequently utilize it within the code.

Example

<html>

<head>

	<title>Functions!!!</title>

	<script type="text/javascript">

function myfirstFunction()  

      {

	document.write("This is just a simple user-defined  function.<br />");

      }

		myfirstFunction();

	</script>

</head>

<body>

</body>

</html>

In the previously mentioned program, a function named "myfirstFunction" has been established. Within the function's definition, we utilize the document.write; method to output the message "This is just a simple user-defined function." To display this message, it is necessary to invoke the function, as demonstrated in the program.

Output

To invoke the function from a different location within the script, we simply need to use its name, as demonstrated in the following example:

Example

Example

<html>

<head>

<script type = "text/javascript">

function sayhi() {  

document.write ("Hello there!");

         }

</script>



</head>



<body>

<p>Click the given button to call the function</p>

<form>

<input type = "button" onclick = "sayhi()" value = "Say Hello">

</form>



</body>

</html>

Output

Now click on the given button

Function With Parameters

The function utilized in our program is classified as parameterless, as we have not included any parameters in the parameter list, leaving it void. However, we do have the option to incorporate parameters into our function, and we can specify any quantity of parameters, provided they are separated by commas. These parameters are received by the function, allowing for various operations to be executed on them within the function's body.

Syntax of creating a function with parameters

Example

function functionname( parameter1,parameter2,....parameterN)  

{



Lines of code to be executed/set of instructions to be executed in order to perform a specific task.

}

To gain a clearer understanding of utilizing parameters within functions, we can refer to a practical example:

Program

Example

<html>

<head>

<script type = "text/javascript">

function sayHello(name, age,gender) {  

document.write (name + " is " + age + " years old" + " and gender is " + gender);

         }

</script>

</head>



<body>

<p>Click the following button to call the function</p>

<form>

<input type = "button" onclick = "sayHello(' Isabella', 23,'female')" value = "Say Hello">

</form>

</body>

</html>

In this code, we established a function called "sayHello " which takes three parameters: name, age, and gender, and we defined it within the head portion of the HTML document. To utilize this function, we incorporated a button using the form tag in the body section of the program and supplied the values as arguments. When the user clicks on this button, our function is invoked and runs accordingly.

Output

Now click on the given button.

Function with return statement

In JavaScript, it is possible to define functions that can yield a value. To accomplish this, one must employ the return statement; however, it is crucial for this statement to be the final line within the function's body (or its definition). Additionally, it is important to note that a function may only contain a single return statement. If multiple return statements are included within a function, only the first one encountered during the program's execution will be acknowledged.

Syntax of function with return statement

Example

Function functionname(arg1, arg2)



{



  Set of instructions to be executed



return val1;



}

To grasp the application of the return statement within a function, we can utilize an illustrative example:

Example

Example

<html>  

<head>  

<script type = "text/javascript">  

function combinestring(string1, string2) { // function1  

var completeString;  

completeString = string1 + string2;  

return completeString;  

         }  

function secondFunction() {  

var result;  

result = combinestring('Java', 'Script');  

document.write (result );  

         }  

</script>  

</head>  

  

<body>  

<p>Click the following button to see the function in action</p>  

<form>  

<input type = "button" onclick = "secondFunction()" value = "Call Function">  

</form>  

  

</body>  

</html>

Explanation of the program

In this code, we have established two functions: combinestring(string1, string2) and secondFunction. Their definitions are outlined in the head section of the HTML document.

Function 1

Within the implementation of the function "combineString(string1, string2)", we established a variable designated as "completestring" to hold the result of merging the two input strings. In order to provide the value contained in this variable back to the caller, we employed a return statement, as demonstrated in the code.

Function2

Within the implementation of secondfunction, a variable named "result" has been initialized. We invoke our initial function titled "completeString(string1, string2)". Upon the execution of "secondfunction", the "completeString(string1, string2)" function is also executed, and the outcome of this function is assigned to the variable "result".

Upon the conclusion of the execution of the "completeString(string1, string2)" function, the output is assigned to the variable "result." Subsequently, within the body of the "secondfunction" function, we utilize the document.write statement to present the value contained in the "result" variable.

In order to invoke the "secondfunction," we have designed a button for the user by utilizing the form tag. Upon clicking this button, the secondfunction will be activated.

Note: As you can see in the program, we have used the "return" statement as the last instruction in the body of the "completeString(string1, string2) function.

Output

Click on the given button.

Input Required

This code uses input(). Please provide values below: