A function is the building block for a programming language. Additionally, it comprises of a set of statements designated to accomplish a specific task. The basic idea is to put some commonly or repeatedly done tasks together and make a function. Therefore, instead of writing the same code again and again for different inputs, the user can invoke that function. JavaScript also supports the use of functions just like other programming languages. In this article, we will cover the following topics related to functions in JavaScript:

  • What is Function in JavaScript?
    • How to define a function in JavaScript?
    • How to Call a function in JavaScript?
    • Function Naming convention
    • Rules to create a function in JS
    • Advantages of Functions
  • Different types of Functions in JavaScript
  • Different types of Advance Functions in JavaScript

What are the Functions in JavaScript?

Unlike other programming languages, JavaScript functions are objects. In other words, it is an instance of the Function type. Consequently, it has properties and methods like other objects. Also, the name of a function is merely a pointer that points to the function object. Let's discuss in the below sections, how to declare and invoke functions in JavaScript.

How to define functions in JavaScript?

Function in JavaScript is defined using the "function" keyword, followed by the name of the function and the optional parameters within brackets. The diagram below shows the basic anatomy of declaring a function in JavaScript:

 Functions in JavaScript

Let's discuss all the parts of the function declaration:

  1. The keyword "function" signifies the start of the function declaration. Additionally, it is a mandatory part of any function declaration.
  2. The function name is specified next to the keyword function. We can omit this part for certain function types.
  3. The parameters of the function come within the parenthesis. Moreover, they are an optional part of the function declaration.
  4. The function body generally comes between the curly brackets({}). Additionally, it is the part where the implementation of the main logic of the function happens.
  5. The last statement of the function is generally a return statement, which starts with a keyword return. The value or expression follows it, which is an expectation from the function to return.

How to Call functions in JavaScript?

Defining a function does not execute it. Describing it names the function and specifies what to do at invoking the function.

Calling the function performs the specified actions with the indicated parameters. After defining a function, the next step is to call them to make use of the function. We can call a function by using the function name separated by the value of parameters enclosed between parenthesis and a semicolon at the end. Below syntax shows how to call functions in JavaScript:

Syntax:

functionName( Value1, Value2, ..);

where,

  • functionName is the name of the function which needs invoking.
  • Value1, Value2 are the various parameters which the function expects.

Function Naming convention

Apart from following the above structure for a function declaration, JavaScript also enforces a few conditions about how to provide function names. Some of them are:

  • Function names must start with a letter, underscore, or a dollar sign.
  • After the first letter/underscore/dollar, we can use numbers.
  • Function names in JavaScripts are case sensitives.
  • The code of the function will come inside curly brackets.

Rules to create functions in JavaScript

In addition to the conditions for naming functions, JavaScript has also defined a few rules, which user should adhere to while defining a function. Few of those rules are:

  • All the functions in JavaScript should start with a function keyword.
  • Function names should be unique.
  • Parameters passed to function should be comma-separated.

Advantages of Functions

Like any other language, functions also play a significant role in Javascript. Some of the benefits of using functions or methods are as follows:

  • Reusability of Code: We can call the function as many times we need in the script, using this way, it saves the coding efforts.
  • Ease of Maintainability: Since we are keeping reusable code in the functions and calling those functions when it is required, it will be easy to debug and maintain the code.

Different types of Functions in JavaScript

JavaScript functions can be categorized into various types based on the parameters and return values. Let's discuss them in detail in the below sections:

Function without Parameters

A function can create without passing any values or parameters to it, so basically creating a function with empty parentheses().

Syntax: Function without parameters:

function function_name(){
   //code to perform the required action 
}

Calling a function without any parameters:

Below is a simple program that illustrates the basic working (defining and calling) of a function:

<html>
<head>
    <script>function myFunction() {
        document.write("Tools QA....!!!");
    }</script>
</head>
<body onload=myFunction()></body>
</html>

Save the file with name functions.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:

 JavaScript Functions Example

In the above code snippet, we are creating a function by name myFunction without any parameters. This function is going to print "Tools QA….!!!", we are calling the created function when the body of the HTML page is loaded.

Function with Parameters

Function parameters come inside the parentheses() in the function definition. These are the additional data passed to functions which need to be manipulated for the calculations and have the following characteristics:

  • The naming conventions for the parameters follow the same rules as naming a variable in JavaScript.
  • As JavaScript is a dynamically typed scripting language, a function parameter can have a value of any data type.
  • Inside the function, all the parameters behave as a local variable.

Syntax: Function with parameters:

function function_name(parameter1, parameter2, ……){

   //code to perform the required action

}

Calling a function with parameters:

Below is a sample program, which shows how to define and invoke a function that accepts parameters:

<html>
	<body>

		<h1>JavaScript: Demonstrating function with parameters</h1>

	    <script>
	    	// Create a function which accepts two parameters
	    	function myFunction(personName, siteName) {
	        	document.write("Hello ",personName,"!  Welcome to ",siteName);
	    	}

	    	// Invoke the function with parameters
	    	myFunction('Lakshay','ToolsQA')
	    </script>

	    
	</body>
</html>

Save the file with name functionWithParameters.html and open it a browser. It should show the output as:

JS Function with Parameters

In the above code, we are creating a function by name myFunction, which accepts two parameters personName and siteName. While invoking the function at line number 13, whatever parameters pass to the function, they will print using the document. write() function of HTML at line number 9.

Function with a return value

Return is a keyword used to return any data to a caller who is calling the function. When JavaScript reaches a return statement, the function will stop executing, and the return value is "returned" back to the "caller".

Syntax: Returning a value from function:

function function_name(parameters){

  //code to perform certain actions

  return output_value;

}

Calling a function which returns a value:

Let's modify the above-written program so as instead of printing the value, it returns that value:

<html>
	<body>

		<h1>JavaScript: Demonstrating function with return value</h1>

	    <script>
	    	// Create a function which accepts two parameters and return a string
	    	function myFunction(personName, siteName) {
	        	return "Hello "+ personName + "!  Welcome to " + siteName;
	    	}

	    	// Invoke the function with parameters and save the return value in a variable
	    	var message = myFunction('Lakshay','ToolsQA');
	    	document.write(message);
	    </script>

	    
	</body>
</html>

Save the file with name functionWithReturnValues.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:

 JavaScript Function with return values

In the above code, we are creating a function that takes two parameters personName and siteName as parameters and returns a welcome message by concatenating the inputs parameters with few strings. Then while invoking the function at line no 13, we store the return value in a variable "message" and then print the variable in the next line. So, it makes it clear that whatever values we return from a function using the "return" keyword, can be stored in a variable while invoking the function.

Different types of Advance Functions in JavaScript

Apart from the core-concepts, as mentioned above related to functions, JavaScript also provides some advanced concepts related to functions. In the below section, we will cover a few of them:

Default Parameters in a function

In JavaScript, parameters of functions default to "undefined". E.g., *if we modify the above-written program and while invoking the function, don't pass the second parameter, JavaScript will assume the value of that parameter as "undefined":

<html>
	<body>

		<h1>JavaScript: Demonstrating default value of a parameter</h1>

	    <script>
	    	// Create a function which accepts two parameters and return a string
	    	function myFunction(personName, siteName) {
	        	return "Hello "+ personName + "!  Welcome to " + siteName;
	    	}

	    	// Invoke the function, but don't pass the 2nd parameter
	    	var message = myFunction('Lakshay');
	    	document.write(message);
	    </script>

	    
	</body>
</html>

Save the above file as defaultParameters.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:  Default value of a parameter

The above screenshot clearly shows that the value of the 2nd parameter is "undefined". So, JavaScript functions don't raise an error when the parameters don't pass while invoking the function, but instead, assume their default value as "undefined".

Anonymous functions

An anonymous function is a function whose declaration happened without any named identifier to refer to it. As such, an unknown function is usually not accessible after its initial creation.

The below code snippet shows an example of how to declare and invoke an anonymous function:

<html>
	<body>

		<h1>JavaScript: Demonstrating anonymous Function</h1>

	    <script>
	    	// Create a anonymous function which accepts two parameters and return a string
	    	var message = function (personName, siteName) {
	        	return "Hello "+ personName + "!  Welcome to " + siteName;
	    	}('Lakshay','ToolsQA'); // Parameters are passed while invoking the method itself

	    	document.write(message);
	    </script>

	    
	</body>
</html>

Save the above file as anonymousFunction.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:

 JS Anonymous functions

As we can see from the above code snippet and screenshot, the declaration of the function at line 8 happened without any name. Also, the function invoked at the same time itself inline 10, where we just invoked the function by passing the needed parameters. So, as we mentioned above, the anonymous function is declared and invoked at the same place, as due to missing function name, it will not be available and accessible elsewhere in the program.

Nested Functions

Since a function returns a value, it can also return a function as a value. So JavaScript allows us to define a function inside another function and return it.

The following code snippet demonstrates it:

<html>
	<body>

		<h1>JavaScript: Demonstrating nested functions</h1>

	    <script>
	    	// Create a function which accepts two parameters and return a string
	    	function myFunction(personName, siteName) {

	    		// Define the Nested Function 
	    		function siteMessage(personName,siteName) 
	    		{ 
	    		
	    			return "Hello "+ personName + "!  Welcome to " + siteName;
	    		}

	        	// Return the nested function
	        	return siteMessage(personName,siteName);
	    	}

	    	// Invoke the function with parameters and save the return value in a variable
	    	var message = myFunction('Lakshay','ToolsQA');
	    	document.write(message);
	    </script>
	</body>
</html>

Save the above file as nestedFunction.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:

 JS Nested Functions

It is clearly evident from the above screenshot that how we declared a nested function siteMessage() inside the global function myFunction() and how the myFunction() function returns a function call using the return statement. So instead of returning a variable at line 18, the function returned a nested function, which in turn returns the concatenated message.

Key Takeaways

  • JavaScript supports functions whose declaration can happen both with and without parameters. Additionally, they can return values using the "return" keyword.
  • Moreover, the named functions' declaration happens in one place, and their invoking happens using function names at other places. Whereas Anonymous functions declare and invoke at the same place.
  • *JavaScript defines the default value of a function parameter as "undefined".
  • In addition to the above, it supports nested functions, which are the functions defined inside other functions.
  • JavaScript functions can also return functions as a return value.

Let's move to the next article to dive deep more to understand various Operators in javaScript.

JavaScript Variables
JavaScript Variables
Previous Article
JavaScript Operators
JavaScript Operators
Next Article
Arunkumar Chandra
Test USer
Reviewers
Ravinder Singh's Photo
Ravinder Singh

Similar Articles

Feedback