Function declaration and calling

You can package up multiple statements into a function. Functions in JavaScript are declared using the function keyword.

The statements contained by a function are encompassed by braces ({ and }) and are referred to as the code block.

JavaScript is a case-sensitive language, and the keyword function must be lowercase.

The basic syntax is as follows:


function functionName(arg0, arg1,...,argN) { 
    statements 
}

To call the say() function:

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">

        function say(name, message) { 
            document.writeln("Hello " + name + ", " + message); 
        } 
        say("JavaScript", "how are you today?"); 
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

Functions in JavaScript need not specify a return value. Functions can return a value by using the return statement followed by the value to return.

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
    
        function sum(num1, num2) { 
            return num1 + num2; 
        } 
        
        var result = sum(5, 10); 
        document.writeln(result)
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

The code after a return statement will not be executed.

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
    
        function sum(num1, num2) { 
            return num1 + num2;
            document.writeln("Hello world"); //never executed 
        } 
        var result = sum(5, 10); 
        document.writeln(result)
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

To have more than one return statement in a function:

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
    
        function diff(num1, num2) { 
            if (num1 < num2) { 
                return num2 - num1; 
            } else { 
                return num1 - num2; 
            } 
        } 
        var result = diff(5, 10); 
        document.writeln(result)

       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

The return without a value.

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
    
        function sayHi(name, message) { 
            document.writeln("Hello " + name + ", " + message); 
            return; 
        } 
        sayHi("name","how are you");
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

Strict mode places several restrictions on functions:

  • No function can be named eval or arguments.
  • No named parameter can be named eval or arguments.
  • No two named parameters can have the same name.
Home 
  JavaScript Book 
    Language Basics  

Function:
  1. Function declaration and calling
  2. Functions with Parameters
  3. Function Arguments