Page 139 - CITS - Computer Software Application -TT
P. 139

COMPUTER SOFTWARE APPLICATION - CITS



           Why Functions?

           With functions you can reuse code
           You can write code that can be used many times.
           You can use the same code with different arguments, to produce different results.
           The () Operator
           The () operator invokes (calls) the function:
           Example

           Convert Fahrenheit to Celsius:
           function to Celsius (fahrenheit) {
             return (5/9) * (fahrenheit-32);
           }

           let value = to Celsius(77);
           Accessing a function with incorrect parameters can return an incorrect answer:
           Example
           function to Celsius (fahrenheit) {
             return (5/9) * (fahrenheit-32);

           }
           let value = to Celsius();
           Accessing a function without () returns the function and not the function result:
           Example

           function to Celsius (fahrenheit) {
             return (5/9) * (fahrenheit-32);
           }
           let value = to Celsius;
           Note
           As you see from the examples above, toCelsius refers to the function object, and toCelsius() refers to the function
           result.
           Functions Used as Variable Values
           Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.

           Example
           Instead of using a variable to store the return value of a function:
           let x = to Celsius(77);
           let text = “The temperature is “ + x + “ Celsius”;

           You can use the function directly, as a variable value:
           let text = “The temperature is “ + to Celsius(77) + “ Celsius”;
           Local Variables
           Variables declared within a JavaScript function, become LOCAL to the function.
           Local variables can only be accessed from within the function.
           Example

           // code here can NOT use carName


                                                           126

                             CITS : IT&ITES - Computer  Software Application - Lesson 37 - 46
   134   135   136   137   138   139   140   141   142   143   144