Table of Contents

    Functions in JavaScript: Syntax, Types, and Examples

    Functions in JavaScript: Syntax, Types, and Examples

    JavaScript Functions

    JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse the code.

    A function is a set of statements that performs a tasks or calculates a value. Functions may also take inputs, process them and return the output.

    Advantage of JavaScript function

    There are mainly two advantages of JavaScript functions.

    1. Code reusability: We can call a function several times so it save coding.
    2. Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a common task.

    JavaScript Function Syntax

    The syntax of declaring function is given below.

    function functionName([arg1, arg2, ...argN]){  
     //code to be executed  
    }

    JavaScript Functions can have 0 or more arguments.

    JavaScript Function Example

    Let’s see the simple example of function in JavaScript that does not has arguments.

    
    <script>  
    function msg(){  
    alert("hello! this is message");  
    }  
    </script>  
    <input type="button" onclick="msg()" value="call function"/> 
    

    Like most programming languages, function is a piece of code that can be isolated to be called multiple times. Example of a function:

    function Hello(string)
    {
        return "Hello" + " " + string;
    }
    Hello( "Tom");  /* returns "Hello Tom" */
    Function as value

    Functions are values in JavaScript. A function can be assigned as a value to a variable.

        var f = function foo()
        {
            console.log("Hello");
        };
        f();  /*  returns "Hello" */
    Function as argument

    A function can be passed as an argument to another function.

    var f = function()
    {   console.log("Hello");
    };
    var executor = function(fn)
    {  fn();
    }
    executor(f);  /* returns "Hello" */
    ```
    Function as property

    Functions can be added as a property to an object.

    var myObj = {
     "testProp" : true
    };
    myObj.prop1 = function() {
     console.log ("Function in object");
    };
    myObj.prop1();
    Function arguments

    A function can accept a varied number of arguments. i.e., a function "add" can be called by passing a different number of arguments different times. This is possible using an implicit argument by JavaScript called arguments.

    var add = function()
    {  var i, sum = 0;
      for (i=0; i< arguments.length; i++)
     {  sum += arguments[i];
      }
      return sum;
    };
    
    console.log(add(1,2,3,4,5));  /* 5 arguments*/
    console.log(add(1,2,3,4));  /* 4 arguments*/