·  JavaScript – Syntax – Terms – Function

 

- Info:

  - This tutorial shown how to use functions in JavaScript.

 

- Variable Scope:

  - If you declare a variable using var inside a function, variable will be visible only inside that function (local variable).

    Local variable is destroyed when you exit function.

  - If you declare a variable without using var inside a function, or if you declare variable outside any function (no metter

    if you use var or not) that variable will be visible both and outside of all the functions (global variable).

    Global variable is destroyed when page is closed.

 

- Example:

  - Create D\Temp\JavaScript\Test.html

 

    Test.html

    <script> 

   

      //RETURN VALUES.-----------------------------------------------------

            noReturnValue();

      ret = returnValue  (); document.write(ret+"<br>");

      

      function noReturnValue(){

        document.write("This function doesn't return any value.<br>");

        //No return value.

      }

      

      function returnValue  (){

        document.write("This function returns variable:");

        return 10;

      } 

   

      //PARAMETERS. -------------------------------------------------------

            noParameters();

      ret = parameters  (10,2);

      

      function noParameters(){

        document.write("This function expects no input parameters.<br>");

      }

      

      function parameters(p1, p2){

        document.write("Input parameters were: "+p1+", "+p2);

      } 

 

      //VARIABLES SCOPE.----------------------------------------------------

          var1 = 10;       //GLOBAL

      var var2 = 20;       //GLOBAL

      testScope();

      

      //DISPLAY VARIABLES.

      document.write("var1  = " + var1  + "<br>");

      document.write("var2  = " + var2  + "<br>");

      document.write("var3  = " + var3  + "<br>");

      document.write("local = " + local + "<br>");  //local is not defined.

      

      function testScope(){

        

        //CREATE VARIABLES.

            var3  = 30;    //GLOBAL

        var local = 40;    //LOCAL

        

        //DISPLAY VARIABLES.

        document.write("var1  = " + var1  + "<br>");

        document.write("var2  = " + var2  + "<br>");

        document.write("var3  = " + var3  + "<br>");

        document.write("local = " + local + "<br>");

        

        //CHANGE GLOBAL VARIABLES.

        var1 = 100;

        var2 = 200;

        

      } 

   

    </script>