Learn Functions in JavaScript in 5 Minutes

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.  If you have a few lines of code that needs to be used several times, you can create a function including the repeating lines of code and then call the function wherever you want.

Creating a Function
  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:
?
1
2
3
4
5
6
7
function functionname()
{
  lines of code to be executed 
}
Try this yourself:
This code is editable. Click Run to Execute


1
2
    <html>
3
4
    <head>
5
6
    <title>Functions!!!</title>
7
8
    <script type="text/javascript">
9
10
    function myFunction()
11
12
    {
13
14
    document.write("This is a simple function.<br />");
15
16
    }
17
18
    myFunction();
19
20
    </script>
21
22
    </head>
23
24
    <body>
25
26
    </body>
27
2
    </html> 
You can create functions with arguments as well. Arguments should be specified within parenthesis
Syntax:
?
1
2
3
4
5
6
7
function functionname(arg1, arg2)
{
  lines of code to be executed 
}
Try this yourself:
This code is editable. Click Run to Execute
1
2
    <html>
3
4
    <head>
5
6
    <script type="text/javascript">
7
8
    var count = 0;
9
10
    function countVowels(name)
11
12
    {
13
14
    for (var i=0;i<name.length;i++)
15
16
    {
17
18
     if(name[i] == "a" || name[i] == "e" || name[i] == "i" || name[i] == "o" || name[i] == "u")
19
20
       count = count + 1;
21
22
    }
23
24
    document.write("Hello " + name + "!!! Your name has " + count + " vowels.");
25
26
    }
27
28
    var myName = prompt("Please enter your name");
29
30
    countVowels(myName);
31
32
    </script>
33
34
    </head>
35
36
    <body>
37
38
    </body>
39
40
    </html> 
You can also create functions that return values. Inside the function, you need to use the keyword returnfollowed by the value to be returned.
Syntax:
?
1
2
3
4
5
6
7
8
9
function functionname(arg1, arg2)
{
  lines of code to be executed
  return val1;
}
Try this yourself:
This code is editable. Click Run to Execute
1
2
    <html>
3
4
    <head>
5
6
    <script type="text/javascript">
7
8
    function returnSum(first, second)
9
10
    {
11
12
    var sum = first + second;
13
14
    return sum;
15
16
    }
17
18
    var firstNo = 78;
19
20
    var secondNo = 22;
21
22
    document.write(firstNo + " + " + secondNo + " = " + returnSum(firstNo,secondNo));
23
24
    </script>
25
26
    </head>
27
28
    <body>
29
30
    </body>
31
32
   </html>
33