Computer >> Computer tutorials >  >> Programming >> Javascript

What are different ways of defining functions in JavaScript?


The following are some of the ways of defining functions in JavaScript −

Function definition 

The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.

Here’s an example showing normal function definition −

<script>
   <!--
      function Display()
      {
         alert("Hello World!");
      }
   //-->
</script>

Immediately Invoked Functions

Another way of defining functions in JavaScript is to use Immediately Invoked Functions. The purpose of wrapping is to the namespace and control the visibility of member functions. It wraps the code inside a function scope and decreases clashing with other libraries. This is what we call Immediately Invoked Function Expression (IIFE) or Self Executing Anonymous Function.

Syntax

Here’s the syntax −

(function() {
   // code
})();

As you can see above, the following pair of parentheses converts the code inside the parentheses into an expression −

function(){...}

In addition, the next pair, i.e. the second pair of parentheses continues the operation. It calls the function, which resulted from the expression above.

Anonymous Functions

Anonymous functions are always loaded using a variable name. Anonymous, as the name suggests, allows creating a function without any names identifier. It can be used as an argument to other functions. Call them using a variable name −

This is how JavaScript anonymous functions can be used −

var func = function() {
   alert(‘This is anonymous');
}
func();

Example

//anonymous function
var a = function() {
   return 5;
}

Function Constructors

The function() constructor is used in JavaScript to create a new function object. The objects created are parsed when the function is created.

You can try to run the following code to learn how to work with function() constructor −

<html>
   <body>
      <script>
         var num = new Function('p', 'q', 'r', 'return p * q * r');
         document.write("Value after multiplication: "+num(5, 2, 9));
      </script>
   </body>
</html>