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

COMPUTER SOFTWARE APPLICATION - CITS




           •  When explicitly called from JavaScript code.
           •  Automatically executed, such as in self-invoking functions.
           Function Definition:
           Before, using a user-defined function in JavaScript we have to create one. We can use the above syntax to
           create a function in JavaScript. A function definition is sometimes also termed a function declaration or function
           statement. Below are the rules for creating a function in JavaScript:
           •  Every function should begin with the keyword function followed by,

           •  A user-defined function name that should be unique,
           •  A list of parameters enclosed within parentheses and separated by commas,
           •  A list of statements composing the body of the function enclosed within curly braces {}.
           Example 2: This example shows a basic declaration of a function in javascript.
           •  JavaScript
           function calcAddition(number1, number2) {

               return number1 + number2;
           }
           console.log(calcAddition(6,9));
           Output

           15
           In the above example, we have created a function named calcAddition,
           •  This function accepts two numbers as parameters and returns the addition of these two numbers.
           •  Accessing the function with just the function name without () will return the function object instead of the
              function result.
           There are three ways of writing a function in JavaScript:
           Function Declaration:
           It declares a function with a function keyword. The function declaration must have a function name.
           Syntax:

           function NSTI(paramA, paramB) {
               // Set of statements
           }
           Function Expression:

           It is similar to a function declaration without the function name. Function expressions can be stored in a variable
           assignment.
           Syntax:

           let NSTI= function(paramA, paramB) {
               // Set of statements
           }
           Example 3: This example explains the usage of the Function expression.
           •  Javascript
           const square = function (number) {

                 return number * number;
           };


                                                           128

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