Fundamentals of Functions

Introduction

A function is a section of code used to solve a certain problem, or usually to deal with a small issue. There are various categories of functions you will use: those you create and those that are already available.

Practical LearningPractical Learning: Introducing Functions

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the middle frame of the New Project dialog box, make sure ASP.NET Web Application (.NET Framework) is selected.
    Change the Name to PayrollPreparation2
  4. Click OK
  5. In the ASP.NET Web Application dialog box, make sure the MVC icon is selected.
    Click OK
  6. In the Solution Explorer, right-click Content -> Add -> New Item...
  7. In the left list of the Add New Item dialog box, under Visual C#, expand Web, and click Markup
  8. In the middle list, click Style Sheet
  9. Change the file Name to PayrollPreparation
  10. Click Add
  11. Change the document as follows:
    body {
        background-color: white;
    }
    
    .bold        { font-weight: 600;   }
    .small       { width:       100px; }
    .large-text  { width:       120px; }
    .delimiter   { margin:      auto;
                   width:       700px; }
    .common-font { font-family: Georgia, Garamond, 'Times New Roman', serif; }
  12. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  13. Change the document as follows:
    using System.Web.Optimization;
    
    namespace PayrollPreparation2
    {
        public class BundleConfig
        {
            // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js"));
    
                bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.validate*"));
    
                // Use the development version of Modernizr to develop with and learn from. Then, when you're
                // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                            "~/Scripts/modernizr-*"));
    
                bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                          "~/Scripts/bootstrap.js"));
    
                bundles.Add(new StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/site.css",
                          "~/Content/PayrollPreparation.css"));
            }
        }
    }
  14. In the Solution Explorer, expand Controllers, and click HomeController.cs
  15. In the class, create a method named PayrollEvaluation as follows:
    using System.Web.Mvc;
    
    namespace PayrollPreparation1.Controllers
    {
        public class HomeController : Controller
        {
            . . .
    
            public ActionResult PayrollEvaluation() => View();
        }
    }
  16. In the class, right-click PayrollEvaluation() -> Add View...
  17. Make sure the View Name text box is displaying PayrollEvaluation.
    Click Add
  18. Change the document as follows:
    @{
        ViewBag.Title = "Payroll Evaluation";
    }
    
    <h2 class="common-font text-center bold">Payroll Evaluation</h2>
    
    <hr />
    
    <div class="delimiter common-font">
        <table>
            <tr>
                <td class="large-text bold">Hourly Salary:</td>
                <td><span class="form-control small" id="hourlySalary"></span></td>
            </tr>
        </table>
    
        <table class="table table-striped">
            <tr>
                <td class="large-text bold">&nbsp;</td>
                <td class="bold text-center">Monday</td>
                <td class="bold text-center">Tuesday</td>
                <td class="bold text-center">Wednesday</td>
                <td class="bold text-center">Thursday</td>
                <td class="bold text-center">Friday</td>
            </tr>
            <tr>
                <td class="bold">Time Worked:</td>
                <td><span class="form-control small" id="monday"></span></td>
                <td><span class="form-control small" id="tuesday"></span></td>
                <td><span class="form-control small" id="wednesday"></span></td>
                <td><span class="form-control small" id="thursday"></span></td>
                <td><span class="form-control small" id="friday"></span></td>
            </tr>
            <tr>
                <td class="bold">Daily Salary:</td>
                <td><span id="salaryMonday"></span></td>
                <td><span id="salaryTuesday"></span></td>
                <td><span id="salaryWednesday"></span></td>
                <td><span id="salaryThursday"></span></td>
                <td><span id="salaryFriday"></span></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="bold">Weekly Salary:</td>
                <td><span id="weeklySalary"></span></td>
            </tr>
        </table>
    </div>
  19. In the Solution Explorer, right-click Scripts -> Add -> New Item...
  20. In the left list of the New Item dialog box, under Visual C# and under Web, click Scripts
  21. In the middle list, click TypeScript File
  22. Change the file Name to TimeSheetEvaluation
  23. Click Add

Creating a Function

There are various ways to create a function. In a TypeScript file, the primary formula to create a function is:

function function-name(){}

You can start function, a name, and (){}. Based on this formula, you will give a name to your function. To name your function, you can use the camelCase. In this case:

After the name, add some parentheses. In some cases, the parentheses will be empty. The section just after { to } is the body of the function. In the body of the function, you can create 0, 1, or as many statements as you need, such as declaring one or more variables, etc. If a function contains one statement, you can create it in a single line. Here is an example:

function move() { let number; }

If your function contains many statements, you can write each statement on its own line. A suggestion is to indent each line of code.

Practical LearningPractical Learning: Creating a Function

Calling a Function

Introduction

When you decidee to use a function, you are said to call the function. To call a function, type its name followed by parentheses, and a semicolon.

Practical LearningPractical Learning: Calling a Function

  1. Click the TimeSheetEvaluation.ts tab and change the document as follows:
    function calculate() {
        const hSalary: number = 26.74;
        const mon: number = 8.50;
        const tue: number = 10.50;
        const wed: number = 8.00;
        const thu: number = 9.50;
        const fri: number = 10.00;
    
        const timeWorked: number = mon + tue + wed + thu + fri;
        const weeklySalary: number = timeWorked * hSalary;
    
        document.querySelector("#hourlySalary").innerHTML = hSalary.toFixed(2);
        document.querySelector("#monday").innerHTML = mon.toFixed(2);
        document.querySelector("#tuesday").innerHTML = tue.toFixed(2);
        document.querySelector("#wednesday").innerHTML = wed.toFixed(2);
        document.querySelector("#thursday").innerHTML = thu.toFixed(2);
        document.querySelector("#friday").innerHTML = fri.toFixed(2);
    
        document.querySelector("#salaryMonday").innerHTML = (mon * hSalary).toFixed(2);
        document.querySelector("#salaryTuesday").innerHTML = (tue * hSalary).toFixed(2);
        document.querySelector("#salaryWednesday").innerHTML = (wed * hSalary).toFixed(2);
        document.querySelector("#salaryThursday").innerHTML = (thu * hSalary).toFixed(2);
        document.querySelector("#salaryFriday").innerHTML = (fri * hSalary).toFixed(2);
    
        document.querySelector("#weeklySalary").innerHTML = weeklySalary.toFixed(2);
    }
    
    calculate();
  2. Click the PayrollEvaluate.cshtml tab to access the view
  3. Change the document as follows:
    @{
        ViewBag.Title = "Payroll Evaluation";
    }
    
    <h2 class="common-font text-center bold">Payroll Evaluation</h2>
    
    <hr />
    
    <div class="delimiter common-font">
        <table>
            <tr>
                <td class="large-text bold">Hourly Salary:</td>
                <td><span class="form-control small" id="hourlySalary"></span></td>
            </tr>
        </table>
    
        <table class="table table-striped">
            <tr>
                <td class="large-text bold">&nbsp;</td>
                <td class="bold text-center">Monday</td>
                <td class="bold text-center">Tuesday</td>
                <td class="bold text-center">Wednesday</td>
                <td class="bold text-center">Thursday</td>
                <td class="bold text-center">Friday</td>
            </tr>
            <tr>
                <td class="bold">Time Worked:</td>
                <td><span class="form-control small" id="monday"></span></td>
                <td><span class="form-control small" id="tuesday"></span></td>
                <td><span class="form-control small" id="wednesday"></span></td>
                <td><span class="form-control small" id="thursday"></span></td>
                <td><span class="form-control small" id="friday"></span></td>
            </tr>
            <tr>
                <td class="bold">Daily Salary:</td>
                <td><span id="salaryMonday"></span></td>
                <td><span id="salaryTuesday"></span></td>
                <td><span id="salaryWednesday"></span></td>
                <td><span id="salaryThursday"></span></td>
                <td><span id="salaryFriday"></span></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="bold">Weekly Salary:</td>
                <td><span id="weeklySalary"></span></td>
            </tr>
        </table>
    </div>
    
    <script src="~/Scripts/TimeSheetEvaluation.js"></script>
  4. To execute the project, press Ctrl + F5:

    Introduction to Functions - Calling a Function

  5. Close the browser and return to your programming environment

Immediately Calling a Function

In the above TypeScript code, after creating the function, to use it, we had to explicitly call it. In JavaScript, you can create a function that is immediately called when it reaches its last line. To create a function that is immediately called, include its whole definition in parentheses. Outside the parenthese, include new parentheses and a semicolon. Here is an example:

(function calculate() {
    const hSalary: number = 26.74;
    const mon: number = 8.50;
    const tue: number = 10.50;
    const wed: number = 8.00;
    const thu: number = 9.50;
    const fri: number = 10.00;

    const timeWorked: number = mon + tue + wed + thu + fri;
    const weeklySalary: number = timeWorked * hSalary;

    document.querySelector("#hourlySalary").innerHTML = hSalary.toFixed(2);
    document.querySelector("#monday").innerHTML = mon.toFixed(2);
    document.querySelector("#tuesday").innerHTML = tue.toFixed(2);
    document.querySelector("#wednesday").innerHTML = wed.toFixed(2);
    document.querySelector("#thursday").innerHTML = thu.toFixed(2);
    document.querySelector("#friday").innerHTML = fri.toFixed(2);

    document.querySelector("#salaryMonday").innerHTML = (mon * hSalary).toFixed(2);
    document.querySelector("#salaryTuesday").innerHTML = (tue * hSalary).toFixed(2);
    document.querySelector("#salaryWednesday").innerHTML = (wed * hSalary).toFixed(2);
    document.querySelector("#salaryThursday").innerHTML = (thu * hSalary).toFixed(2);
    document.querySelector("#salaryFriday").innerHTML = (fri * hSalary).toFixed(2);

    document.querySelector("#weeklySalary").innerHTML = weeklySalary.toFixed(2);
})();

Introduction to Parameters and Arguments

A Parameter in a Function

When creating a function, you may want to provide one or more values to be used in the body of the function. A value you provide to a function is called a parameter.

In JavaScript, to indicate that a function will need a value, in the parantheses of the function, type a name for the paramer. Here is an example:

function evaluateDailySalary(time) {

}

In TypeScript, you should indicate the data type of a parameter. To do this, after the name of the parameter, type a colon followed by the data type. Here is an example:

function evaluateDailySalary(time: number) {

}

In the body of the function, you can use the parameter. For example, you can involve it in an expression. Here is an example:

function evaluateDailySalary(time: number) {
    let result: number = 15.75 * time;
}

Calling a Function that Uses a Parameter

As seen earlier, to use a function, you must call it. If the function uses a parameter, type the name of the function and its parentheses. In the parentheses, type the desired value of the parameter. The value you provide is called an argument. When you call the function and provide the value of the parameter, you are said to pass an argument to the function. Because you must provide a value for the parameter, its argument is said to be required.

If the value you want to pass as argument will be used only once, you can pass its value directly to the function. If you have the value you want to use, provide it in the parentheses of the function. Here are examples:

function evaluateDailySalary(time: number) {
    let result: number = 15.75 * time;
    document.querySelector("#salaryMonday").innerHTML = result.toFixed(2);
}

function calculate() {
    evaluateDailySalary(6.00);
    evaluateDailySalary(7.50);
    evaluateDailySalary(5.50);
    evaluateDailySalary(8.00);
    evaluateDailySalary(7.00);
}

calculate();

If you may want to use the value more than once, you can first declare a variable, initialize it, and then pass it as argument. Here are examples:

function evaluateDailySalary(time: number) {
    let result: number = 15.75 * time;
    document.querySelector("#salaryMonday").innerHTML = result.toFixed(2);
}

function calculate() {
    const hSalary: number = 15.75;
    const mon: number = 6.00;
    const tue: number = 7.50;
    const wed: number = 5.50;
    const thu: number = 8.00;
    const fri: number = 7.00;

    const timeWorked: number = mon + tue + wed + thu + fri;
    const weeklySalary: number = timeWorked * hSalary;

    document.querySelector("#hourlySalary").innerHTML = hSalary.toFixed(2);
    document.querySelector("#monday").innerHTML = mon.toFixed(2);
    document.querySelector("#tuesday").innerHTML = tue.toFixed(2);
    document.querySelector("#wednesday").innerHTML = wed.toFixed(2);
    document.querySelector("#thursday").innerHTML = thu.toFixed(2);
    document.querySelector("#friday").innerHTML = fri.toFixed(2);

    evaluateDailySalary(mon);

    document.querySelector("#weeklySalary").innerHTML = weeklySalary.toFixed(2);
}

calculate();

A Function With Various Arguments

A Function With Two Parameters

When creating a function, you may want to prepare it to use many parameters. To do this, in the parentheses of the function, type the name of each parameter and separate them with commas. To indicate the type of a parameter, after its name, type a colon followed by the desired type. Here is an example:

function evaluateDailySalary(salary: number, time: number) {

}

In the body of the function, you can use none of the parameters or both parameters.

Practical LearningPractical Learning: Creating a Function of Two Parameters

  1. Click the TimeSheetEvaluation.ts tab and change the document as follows:
    function evaluateDailySalary(day: string, time: number) {
        const hSalary: number = 15.75;
        let result: number = hSalary * time;
        document.querySelector("" + day + "").innerHTML = result.toFixed(2);
    }
    
    . . .

Calling a Function that Uses Two Parameters

If you are calling a function that uses two parameters, provide a value for each parameter in the order the parameters appear in the parentheses of the function.

Practical LearningPractical Learning: Calling a Function that Uses Two Parameters

  1. Change the TimeSheetEvaluation.ts document as follows:
    function evaluateDailySalary(day: string, time: number) {
        const hSalary: number = 15.75;
        let result: number = hSalary * time;
        document.querySelector(day).innerHTML = result.toFixed(2);
    }
    
    function calculate() {
        const hSalary: number = 15.75;
        const mon: number = 6.00;
        const tue: number = 7.50;
        const wed: number = 5.50;
        const thu: number = 8.00;
        const fri: number = 7.00;
    
        const timeWorked: number = mon + tue + wed + thu + fri;
        const weeklySalary: number = timeWorked * hSalary;
    
        document.querySelector("#hourlySalary").innerHTML = hSalary.toFixed(2);
        document.querySelector("#monday").innerHTML = mon.toFixed(2);
        document.querySelector("#tuesday").innerHTML = tue.toFixed(2);
        document.querySelector("#wednesday").innerHTML = wed.toFixed(2);
        document.querySelector("#thursday").innerHTML = thu.toFixed(2);
        document.querySelector("#friday").innerHTML = fri.toFixed(2);
    
        evaluateDailySalary("#salaryMonday", mon);
        evaluateDailySalary("#salaryTuesday", tue);
        evaluateDailySalary("#salaryWednesday", wed);
        evaluateDailySalary("#salaryThursday", thu);
        evaluateDailySalary("#salaryFriday", fri);
    
        document.querySelector("#weeklySalary").innerHTML = weeklySalary.toFixed(2);
    }
    
    calculate();
  2. Click the PayrollEvaluation.cshtml tab to activate it
  3. To execute, on the main menu, click Debug -> Start Without Debugging

    Introduction to Functions - Parameters and Arguments

  4. Close the browser and return to your programming environment

A Function with many Parameters

Depending on your goal, you can create a function that uses as many parameters as you want. All parameters can be of the same type of they can be of different types in the order of your choice. Here is an example:

function evaluateDailySalary(day: string, salary: number, time: number) {

}

In the body of the function, you can use none, some, or all of the parameters.

When calling the function, provide a value for each parameter, in the order the parameters appear in the parentheses of the function.

Practical LearningPractical Learning: Calling a Function that Uses Two Parameters

  1. Click the TimeSheetEvaluation.ts tab and change the document as follows:
    function evaluateDailySalary(day: string, salary: number, time: number) {
        let result: number = salary * time;
        document.querySelector(day).innerHTML = result.toFixed(2);
    }
    
    function calculate() {
        const hSalary: number = 18.37;
        const mon: number = 8.00;
        const tue: number = 9.50;
        const wed: number = 10.00;
        const thu: number = 8.50;
        const fri: number = 7.50;
    
        const timeWorked: number = mon + tue + wed + thu + fri;
        const weeklySalary: number = timeWorked * hSalary;
    
        document.querySelector("#hourlySalary").innerHTML = hSalary.toFixed(2);
        document.querySelector("#monday").innerHTML = mon.toFixed(2);
        document.querySelector("#tuesday").innerHTML = tue.toFixed(2);
        document.querySelector("#wednesday").innerHTML = wed.toFixed(2);
        document.querySelector("#thursday").innerHTML = thu.toFixed(2);
        document.querySelector("#friday").innerHTML = fri.toFixed(2);
    
        evaluateDailySalary("#salaryMonday", hSalary, mon);
        evaluateDailySalary("#salaryTuesday", hSalary, tue);
        evaluateDailySalary("#salaryWednesday", hSalary, wed);
        evaluateDailySalary("#salaryThursday", hSalary, thu);
        evaluateDailySalary("#salaryFriday", hSalary, fri);
    
        document.querySelector("#weeklySalary").innerHTML = weeklySalary.toFixed(2);
    }
    
    calculate();
  2. Click the PayrollEvaluation.cshtml tab to activate it
  3. To execute, on the main menu, click Debug -> Start Without Debugging

    Introduction to Functions - Parameters and Arguments

  4. Close the browser and return to your programming environment

Returning a Value from a Function

Introduction

After performing its operation, a function may produce a value. When that happens, the function is said to return a value. The value can be a type of your choice: number, string, etc.

In TypeScript, when creating a function that returns a value, it is a good idea to indicate the type of value that the value will return. To do this, after the parentheses of the function, type a colon followed by the desired data type. Here is an example:

function specifyPrice() : number {

}

To specify the value that a function must return, just before the closing curly bracket, type return followed by the value that the function must return. You can create a function that simply returns a constant value. Here is an example:

function specifyPrice(): number {
    return 928.45;
}

If the value that the function must return should be used more than once, you can first declare a variable for it, perform the desired operations, and then return that variable. Here is an example:

function add(x: number, y: number): number {
    let result: number = x + y;

    return result;
}

If the value that will be produced is needed only when the function ends, you can write the returning expression after the return keyword.

Practical LearningPractical Learning: Returning a Value From a Function

Calling a Function that Returns a Value

When calling a function that returns a value, you can get that value and use it the same way you would use a value of a variable. When calling the function, you can assign its call to a locally declared variable.

ApplicationPractical Learning: Calling Functions

  1. Change the TimeSheetEvaluation.ts document as follows:
    function add(a: number, b: number, c: number, d: number, e: number): number {
        let result: number = a + b + c + d + e;
    
        return result;
    }
    
    function multiply(x: number, y: number): number {
        return x * y;
    }
    
    function evaluateDailySalary(day: string, salary: number, time: number) {
        let result: number = multiply(salary, time);
        document.querySelector("" + day + "").innerHTML = result.toFixed(2);
    }
    
    function calculate() {
        const hSalary: number = 25.25;
        const mon: number = 7.50;
        const tue: number = 6.50;
        const wed: number = 8.00;
        const thu: number = 7.00;
        const fri: number = 6.00;
    
        const timeWorked: number = add(mon, tue, wed, thu, fri);
        const weeklySalary: number = multiply(timeWorked, hSalary);
    
        document.querySelector("#hourlySalary").innerHTML = hSalary.toFixed(2);
        document.querySelector("#monday").innerHTML = mon.toFixed(2);
        document.querySelector("#tuesday").innerHTML = tue.toFixed(2);
        document.querySelector("#wednesday").innerHTML = wed.toFixed(2);
        document.querySelector("#thursday").innerHTML = thu.toFixed(2);
        document.querySelector("#friday").innerHTML = fri.toFixed(2);
    
        evaluateDailySalary("#salaryMonday", hSalary, mon);
        evaluateDailySalary("#salaryTuesday", hSalary, tue);
        evaluateDailySalary("#salaryWednesday", hSalary, wed);
        evaluateDailySalary("#salaryThursday", hSalary, thu);
        evaluateDailySalary("#salaryFriday", hSalary, fri);
    
        document.querySelector("#weeklySalary").innerHTML = weeklySalary.toFixed(2);
    }
    
    calculate();
  2. Click the PayrollPreparation.cshtml tab to activate it
  3. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Functions Fundamentals - Returning a Value from a Function

  4. Close the browser and return to your programming environment

Techniques of Calling a Function that Returns a Value

As seen above, you can first declare a variable and, when calling a function that returns a value, assign the call to that variable. This is useful if you are planning to use the returning value many times. Here is an example:

function multiply(x: number, y: number): number {
    return x * y;
}
function evaluateDailySalary(day: string, salary: number, time: number) {
    let result: number = multiply(salary, time);
    document.querySelector("" + day + "").innerHTML = result.toFixed(2);
}

If you are not planning to use the returned value many times, you can call the function directly where its returned value is needed. Here is an example:

function multiply(x: number, y: number): number {
    return x * y;
}
function evaluateDailySalary(day: string, salary: number, time: number) {
    document.querySelector("" + day + "").innerHTML = multiply(salary, time).toFixed(2);
}

If the returned value of a function is passed to another function, you can call the function directly in the placeholder of the other calling function.

ApplicationPractical Learning: Calling a Function

  1. Click the TimeSheetsEvalueation.ts tab and change the document as follows:
    function add(a: number, b: number, c: number, d: number, e: number): number {
        return a + b + c + d + e;
    }
    function multiply(x: number, y: number): number {
        return x * y;
    }
    function evaluateDailySalary(day: string, salary: number, time: number) {
        document.querySelector("" + day + "").innerHTML = multiply(salary, time).toFixed(2);
    }
    
    function calculate() {
        const hSalary: number = 30.05;
        const mon: number = 9.50;
        const tue: number = 7.50;
        const wed: number = 10.00;
        const thu: number = 6.00;
        const fri: number = 6.50;
    
        const weeklySalary: number = multiply(add(mon, tue, wed, thu, fri), hSalary);
    
        document.querySelector("#hourlySalary").innerHTML = hSalary.toFixed(2);
        document.querySelector("#monday").innerHTML = mon.toFixed(2);
        document.querySelector("#tuesday").innerHTML = tue.toFixed(2);
        document.querySelector("#wednesday").innerHTML = wed.toFixed(2);
        document.querySelector("#thursday").innerHTML = thu.toFixed(2);
        document.querySelector("#friday").innerHTML = fri.toFixed(2);
    
        evaluateDailySalary("#salaryMonday", hSalary, mon);
        evaluateDailySalary("#salaryTuesday", hSalary, tue);
        evaluateDailySalary("#salaryWednesday", hSalary, wed);
        evaluateDailySalary("#salaryThursday", hSalary, thu);
        evaluateDailySalary("#salaryFriday", hSalary, fri);
    
        document.querySelector("#weeklySalary").innerHTML = weeklySalary.toFixed(2);
    }
    
    calculate();
  2. Click the PayrollEvaluation.cshtml tab to accress it
  3. To execute the application to see the results, on the main menu, click Debug -> Start Without Debugging:

    Returning a Value from a Function

  4. Close the browser and return to your programming environment

A Void function

Not all functions produce a value that other functions need or a value that can be assigned to a variable. When creating a function that doesn't produce a value, specify its return type as void. Here is an example:

function calculate(): void {
 
}

calculate();

Previous Copyright © 2018-2019, FunctionX Next