JavaScript Create & Call Functions with Example

JavaScript Create & Call Functions with Example

What is Function in JavaScript?

JavaScript functions make code reusable. In the function, you can write a block of code. Call the function anywhere and several times in your program. Functions are very important and useful in any programming language because they make the code reusable. If you have a few lines of code that need to be used multiple times, you can create a function including repeating lines of code and then call the function wherever you want.

Here, you will learn-

  • How to Create a Function in JavaScript
  • Function with Arguments
  • JavaScript Return Value

How to Create a Function in JavaScript

  1. Use the keyword function followed by the name of the function.
  2. After the function name, open and close parentheses.
  3. After parenthesis, open and close curly braces.
  4. Within curly braces, write your lines of code.

Syntax:

function functionname()

{

  lines of code to be executed

}

Example – How to Create a Function in JavaScript

<html>
<head>
 <title>Functions!!!</title>
  <script type="text/javascript">
      function myFunction()
      {
      	document.write("This is a simple function.<br />");
      }
      myFunction();
   </script>
</head>
<body>
</body>
</html> 

Function with Arguments

You can create functions with arguments as well. Arguments should be specified within parenthesis

Syntax:

function functionname(arg1, arg2)

{

  lines of code to be executed

}

Example – Function with Arguments

<html>
<head>
  <script type="text/javascript">
    var count = 0;
    function countVowels(name)
    {
      for (var i=0;i<name.length;i++)
      {
              if(name[i] == "a" || name[i] == "e" || name[i] == "i" || name[i] == "o" || name[i] == "u")
              count = count + 1;
      }
    document.write("Hello " + name + "!!! Your name has " + count + " vowels.");
    }
      var myName = prompt("Please enter your name");
      countVowels(myName);
  </script>
</head>
<body>
</body>
</html> 

JavaScript Return Value

You can also create JS functions that return values. Inside the function, you need to use the keyword return followed by the value to be returned.

Syntax:

function functionname(arg1, arg2)

{

  lines of code to be executed

  return val1;

}

Example- JavaScript Return Value

<html>
<head>
  <script type="text/javascript">
    function returnSum(first, second)
        {
          var sum = first + second;
          return sum;
        }
      var firstNo = 55;
      var secondNo = 45;
      document.write(firstNo + " + " + secondNo + " = " + returnSum(firstNo,secondNo));
  </script>
</head>
<body>
</body>
</html>

Conclusion

In this tutorial, you have learned how to create, call and use the function in javascript.

If you want to know more about javaScript functions clickMe

Leave a Reply

Your email address will not be published. Required fields are marked *