JavaScript Functions

Functions are very important and useful in any programming language as they make the code reusable. A function is a block of code which will be executed only if it is called.

How to write code in functions:

<script type="text/javascript">

      function myFunction()

      {

                   document.write("….");

      }

                   myFunction();

</script>

Function with argument:

<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>

Function with return:

<script type="text/javascript">

                        function returnSum(first, second)

        {

          var sum = first + second;

          return sum;

        }

      var firstNo = 78;

      var secondNo = 22;

      document.write(firstNo + " + " + secondNo + " = " + returnSum(firstNo,secondNo));

</script>

Powered  by Codersarts