JavaScript Function (with Examples)

The development of websites has been revolutionized by the flexible programming language JavaScript. Functions are a crucial component of the JavaScript programming language, whether you're creating a straightforward website or a sophisticated web application. Code can be packaged up, made reusable, and better organized overall with the help of functions.

This post is published to cover the following information regarding the function in JavaScript:

What is a Function in JavaScript?

A function in JavaScript is a block of code used to perform a defined task. For example:

function printHello()
{
   console.log("Hello");
}

The above function named printHello() prints the Hello on the console output when it is called or invoked.

How to Create and Define a Function in JavaScript

To create and define a function in JavaScript, follow the syntax given below:

function functionName(para1, para2, para3, ..., paraN)
{
   // block of code to define the function
}

where:

For example:

function message()
{
   document.getElementById("paraOne").innerHTML = "Hey, JavaScript is fun!";
   document.getElementById("paraTwo").innerHTML = "Is not it?";
}

How to Execute a Function in JavaScript

To execute a function, we need to call it. For example:

message();

calls a function named message(). For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="paraOne"></p>
   <p id="paraTwo"></p>

   <script>
      function message()
      {
         document.getElementById("paraOne").innerHTML = "Hey, JavaScript is fun!";
         document.getElementById("paraTwo").innerHTML = "Is not it?";
      }

      message();
   </script>

</body>
</html>
Output

JavaScript Function Return Value

The return statement, or keyword, is used to return a value from a function after executing it. For example:

function cube(num)
{
   return num*num*num;
}

return the cube of num. Therefore, whatever the value we passed to the function named cube(), its cube will be returned. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p>Cube of 5 = <span id="res"></span></p>

   <script>
      function cube(num)
      {
         return num*num*num;
      }

      document.getElementById("res").innerHTML = cube(5);
   </script>

</body>
</html>
Output

Cube of 5 =

The value 5 from cube(5) is initialized or copied to num (the parameter of the cube() function), and using the return statement or keyword, the value of num*num*num, which will be 5*5*5 or 125, will be returned. Therefore, the following statement from the above (previous) example:

document.getElementById("res").innerHTML = cube(5);

will become:

document.getElementById("res").innerHTML = 125;

Wherever the return statement occurs in a function, the execution of the function will be terminated. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="paraOne"></p>
   <p id="paraTwo"></p>

   <script>
      function message()
      {
         document.getElementById("paraOne").innerHTML = "Hey, JavaScript is fun!";
         return;
         document.getElementById("paraTwo").innerHTML = "Is not it?";
      }

      message();
   </script>

</body>
</html>
Output

That is, all the blocks of code available after the return statement in a function will be skipped to execute.

Why do we need a function in JavaScript?

We need a function in JavaScript to wrap some blocks of code in a function so we can use them multiple times. That is, we need a function to execute some block of code or statement multiple times, or the required number of times, without writing that block of code multiple times. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p>Cube of 8 = <span id="resOne"></span></p>
   <p>Cube of 12 = <span id="resTwo"></span></p>
   <p>Cube of 33 = <span id="resThree"></span></p>

   <script>
      function cube(num)
      {
         return num*num*num;
      }

      document.getElementById("resOne").innerHTML = cube(8);
      document.getElementById("resTwo").innerHTML = cube(12);
      document.getElementById("resThree").innerHTML = cube(33);
   </script>
   </script>

</body>
</html>
Output

Cube of 8 =

Cube of 12 =

Cube of 33 =

The code to calculate the cube of a number is created once and used three times. This is how the use of functions benefits us.

Please note: A variable defined inside a function is local to the function where it is defined.

JavaScript Function Examples

Now, I think it is time to give some examples regarding the function in JavaScript to clear up all the remaining doubts. Let me start with a function without parameters.

JavaScript Function without Parameter Example

<!DOCTYPE html>
<html>
<body>

   <script>
      function codescracker()
      {
         console.log("My name is Justin");
         console.log("I'm from 'St. Louis, USA'");
         console.log("I'm here since last 4 years.");
      }
      codescracker();
   </script>

</body>
</html>

The snapshot given below shows the sample output produced by the above JavaScript function, for example:

javascript function example

JavaScript Function with One Parameter Example

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>∛64 = <span id="res"></span></p>

   <script>
      function codescracker(num)
      {
         return Math.cbrt(num);
      }
      document.getElementById("res").innerHTML = codescracker(64);
   </script>
   
</body>
</html>
Output

∛64 =

JavaScript Function with Two Parameters Example

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Gross Salary = $68400 and Tax Deduction@22%</p>
   <p>Actual Salary after Tax Deduction  = <span id="res"></span></p>

   <script>
      function inHandSalary(totalSalary, taxPercentage)
      {
         let taxAmount = (taxPercentage*totalSalary)/100;
         return (totalSalary-taxAmount);
      }
      document.getElementById("res").innerHTML = inHandSalary(68400, 22);
   </script>
   
</body>
</html>
Output

Gross Salary = $68400 and Tax Deduction@22%

Actual Salary after Tax Deduction =

JavaScript Function with Three Parameters Example

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Principle Amount = $60000, Rate of Interest = 7.8%, Time = 4 Years</p>
   <p>Simple Interest based on above values  = <span id="res"></span></p>

   <script>
      function si(p, r, t)
      {
         return ((p*r*t)/100);
      }
      document.getElementById("res").innerHTML = si(60000, 7.8, 4);
   </script>
   
</body>
</html>
Output

Principle Amount = $60000, Rate of Interest = 7.8%, Time = 4 Years

Simple Interest based on above values =

In similar ways, you can pass as many parameters as required to the JavaScript function. It is up to you and your application's requirements.

JavaScript instanceof

The JavaScript instanceof operator is used to check whether the prototype property of a constructor appears in the prototype chain of an object or not. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>
   
   <script>
      function myFun(x, y, z) {
         this.x = x;
         this.y = y;
         this.z = z;
      }
      const v = new myFun(10, 20, 30);
      document.getElementById("xyz").innerHTML = v instanceof myFun;
   </script>
   
</body>
</html>
Output

JavaScript instanceof syntax

The syntax of the instanceof operator in JavaScript is:

object instanceof constructor

It returns a boolean value (true or false).

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!