SimpleTuts.com

JavaScript Function Types

JavaScript functions can be categorized based on their use of arguments and return values. Here are some common types:

1. Function Without Arguments

A function without arguments does not take any parameters.


// Function Without Arguments
function sayHello() {
  console.log("Hello, World!");
}

// Calling the function
sayHello(); // Output: Hello, World!

2. Function With Arguments

A function with arguments takes one or more parameters.


// Function With Arguments
function greet(name) {
  console.log("Hello, " + name + "!");
}

// Calling the function
greet("Alice"); // Output: Hello, Alice!

3. Function With Return Value

A function with a return value returns a result using the return keyword.


// Function With Return Value
function add(a, b) {
  return a + b;
}

// Calling the function
var sum = add(5, 3);
console.log(sum); // Output: 8

4. Function With Arguments and Return Value

A function can take arguments and also return a value.


// Function With Arguments and Return Value
function multiply(a, b) {
  return a * b;
}

// Calling the function
var product = multiply(4, 7);
console.log(product); // Output: 28

All in one Example (HTML file):


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Different types of functions in JavaScript</title>
</head>
<body>
    <button onclick="message1();">Show message1</button>
    <button onclick="message2('John Doe');">Show message2</button>
    <button onclick="message3('John Doe','New York');">Show message3</button>
    <button onclick="getresult();">Result1</button>
    <button onclick="getresult2(8,3);">Result2</button>
    <script src="funtypes.js"></script>
</body>
</html>
Run Code

JavaScript file:


//Types of Functions

//1. Functions without arguments and without return values
function message1(){
	window.alert("Hello world");
}


//2. Functions with arguments and without return values
function message2(name){
	window.alert("Hello "+name+", How are you?");
}

//Multiple arguments
function message3(name,place){
	window.alert("Hello I am "+name+", I am from "+place);
}

//3. Functions without arguments and with return values
function sum(){
	var x=10;
	var y=5;
	var sum=x+y;
	return sum;
}
function difference(){
	var x=10;
	var y=5;
	var dif=x-y;
	return dif;
}
function getresult(){
	var s = sum();
	var d = difference();
	window.alert("Sum = "+s+" and Difference = "+d);
}

//4. Functions with arguments and return values
function sum2(x,y){
	var sum=x+y;
	return sum;
}
function difference2(x,y){
	var dif=x-y;
	return dif;
}
function getresult2(a,b){
	var s = sum2(a,b);
	var d = difference2(a,b);
	window.alert("Sum = "+s+" and Difference = "+d);
}