Fundamentals of Functions

Introduction

A function is a section of code used to solve a specific and relatively small problem.

Creating a Function

To create a function, the primary formula to follow is:

function function-name(){}

Start with the function keyword. A function uses a name. The name of a function is followed by parentheses. Sometimes, the parentheses will be empty. The parentheses of a function are followed by {}. The section from { to } is the body of the function. It will contain the code of the function. If a function is short, you can write everything in one line. Here is an example

<script type="text/javascript" language="JavaScript">
    function move() { var number; }
        
    $(document).ready(function () {
    });
</script>

If a function contains long code, you can write its code on many lines.

Calling a Function

Introduction

Accessing a function is referred to as calling it. To call a function, type its name followed by parentheses, and a semicolon. Here is an example:

@{
    ViewBag.Title = "Employment Application";
}

<h2>Employment Application</h2>

<form name="EmploymentApplication" method="post">
    <table>
        <tr>
            <td><label for="firstName">First Name:</label></td>
            <td><input type="text" id="firstName" /></td>
        </tr>
        <tr>
            <td><label for="lastName">Last Name:</label></td>
            <td><input type="text" id="lastName" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="button" id="creator" value="Create Full Name" /></td>
        </tr>
        <tr>
            <td><label for="fullName">Full Name:</label></td>
            <td><input type="text" id="fullName" /></td>
        </tr>
    </table>
</form>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript" language="JavaScript">
    function getFullName() {
        var fName = $("#firstName").val();
        var lName = $("#lastName").val();
            
        var employeeName = fName + " " + lName;
        $("#fullName").val(employeeName);
    }

    $(document).ready(function () {
        $("#creator").click(function (event) {
            getFullName();
        });
    });
</script>

Immediately Calling a Function

We indicated that you use the name of a function to call it. If you want a function to be called immediately when the webpage is accessed, the formula to create such a function is:

(function() {
	statement1
    statement2
    . . .
    statement_n
})();

In this case, include the whole function definition in parentheses. Outside the parentheses, to call the function, add some empty parentheses. Here is an example:

@{
    ViewBag.Title = "Exercise";
}

<h2>Exercise</h2>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript" language="JavaScript">
    (function () {
        alert("Welcome to the wonderful world of jQuery");
    })();
</script>)

Introduction to Parameters and Arguments

Introduction to the Parameters of a Function

If you want to create a function that will need external values, in the parantheses of the function, enter a name that represents a value. Here is an example:

<script>
    function evaluateWeeklySalary(salary) {
    }
        
    $(document).ready(function () {
    });
</script>

In the body of the function, if you don't want to use a parameter, simply ignore it.

The name you provide to the function is called a parameter. In the body of the function, you can involve the parameter in any operation of your choice wantyou can use or ignore the parameter. Otherwise, . Here is an example:

<script>    
    'use strict';
    function evaluateWeeklySalary(salary) {
        var netPay = salary * 40;

        $(".hourlyRate").val(salary);
    }

    $(document).ready(function () {
    });
</script>

Calling a Function that Uses a Parameter

To call a function that uses a parameter, you must provide a value for the parameter. The value provided in the parentheses of the function is called an argument. The action of providing a value in the parentheses of the function is referred to as passing an argument.

There are various ways you can pass an argument to a function. If you have the value you want to use, provide it in the parentheses of the function. Here is an example:

@{
    ViewBag.Title = "Salary Evaluation";
}

<h2>Salary Evaluation</h2>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td>Hourly Rate:</td>
            <td><input type="text" id="hourlyRate" /></td>
        </tr>
        <tr>
            <td>Net Pay:</td>
            <td><input type="text" id="netPay" /></td>
        </tr>
    </table>
</form>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript" language="JavaScript">
    function evaluateWeeklySalary(salary) {
        var netPay = salary * 40;

        $("#hourlyRate").val(salary);
        $("#netPay").val(netPay);
    }

    $(document).ready(function () {
        evaluateWeeklySalary(24.75);
    });
</script>

If the value is stored in a variable, you can pass the name of the variable to the function. Here is an example:

@{
    ViewBag.Title = "Salary Evaluation";
}

<h2>Salary Evaluation</h2>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td>Hourly Rate:</td>
            <td><input type="text" id="hourlyRate" /></td>
        </tr>
        <tr>
            <td>Net Pay:</td>
            <td><input type="text" id="netPay" /></td>
        </tr>
    </table>
</form>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript" language="JavaScript">
    function evaluateWeeklySalary(salary) {
        var netPay = salary * 40;

        $("#hourlyRate").val(salary);
        $("#netPay").val(netPay);
    }

    $(document).ready(function () {
        var hourlyWage = 37.64;

        evaluateWeeklySalary(hourlyWage);
    });
</script>

A Function With Many Parameters

You can create a function that uses as many parameters as you want. In this case, in its parentheses, provide a name for each parameter. The parameters are separated by commas. Here is an example:

<script>
    function showTimeWorked(timeWorked, payRate) {

    }
<script>

As mentioned earlier, you don't have to use the parameters in the body of the function. Otherwise, in the body of the function, you can use the parameters any appropriate way you want. Here is an example:

<script>
    function evaluateWeeklySalary(payRate, time) {
        var netPay = payRate * time;
    }
</script>

Calling a Function of many Parameters

When calling a function that uses many parameters, you must provide a value for each parameter in the order the parameters appear in the parentheses. Here is an example:

@{
    ViewBag.Title = "Salary Evaluation";
}

<h2>Salary Evaluation</h2>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td>Hourly Rate:</td>
            <td><input type="text" class="hourlyRate" /></td>
        </tr>
        <tr>
            <td>Time Worked:</td>
            <td><input type="text" class="timeWorked" /></td>
        </tr>
        <tr>
            <td>Net Pay:</td>
            <td><input type="text" class="netPay" /></td>
        </tr>
    </table>
</form>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript" language="JavaScript">
    function evaluateWeeklySalary(payRate, time) {
        var netPay = payRate * time;

        $(".hourlyRate").val(payRate);
        $(".timeWorked").val(time);
        $(".netPay").val(netPay);
    }

    $(document).ready(function () {
        evaluateWeeklySalary(17.52, 38);
    });
</script>

Intermediate Characteristics of Functions

Function Overloading

Function overloading is the ability to have two or more functions with the same name in the same document. To have method overloading, each version of the overloaded function must have a different number of parameters. Here is an example:

function calculateBiweeklySalary() {
        
}

function calculateBiweeklySalary(yearlySalary) {

}

function calculateBiweeklySalary(payRate, monthlySalary) {
   
}

Default Arguments

A function is said to have a default argument if the argument is primarily specified. For such a function, a value is assigned to the parameter when the function is created. When such as function is called, you can omit passing an argument. A function can also have many parameters where all of them would have dfeault values. A fuction can have many parameters with only some of them having default values.

The Scope and Lifetime of a Variable

Introduction

The scope of a variable is the extent to which it is available to other sections of a website. To manage this, a variable is said to have local or global scope.

Local Variables

A variable is said to be local if it is declared in the body of a function. Here is an example:

<script>
    function evaluateWeeklySalary() {
        var time = 44.50;
    }
<script>

When a variable is declared locally, it can be accessed only by code inside the same curly brackets. If you try accessing such a variable outside its curly brackets, you would receive an error.

A Web Page-Based Variable

A variable that is declared in a webpage but outside any a function can be accessed by any function in the same webpage. Here is an example:

@{
    ViewBag.Title = "Salary Evaluation";
}

<script>
    var salary = 14.75;
</script>

<h2>Salary Evaluation</h2>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td>Hourly Rate:</td>
            <td><input type="text" class="hourlyRate" /></td>
        </tr>
        <tr>
            <td>Time Worked:</td>
            <td><input type="text" class="timeWorked" /></td>
        </tr>
        <tr>
            <td>Net Pay:</td>
            <td><input type="text" class="netPay" /></td>
        </tr>
    </table>
</form>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript" language="JavaScript">
    'use strict';

    var time = 44.00;

    function evaluateWeklySalary() {
        var netPay = salary * time;

        $(".hourlyRate").val(salary);
        $(".timeWorked").val(time);
        $(".netPay").val(netPay);
    }

    $(document).ready(function () {
        evaluateWeklySalary(salary, time);
    });
</script>

A Function that Returns a Value

Introduction

A function is said to return a value it it produces a value. To create such a function, you have various options. The first thing to do is that, before the closing curly bracket, type the return keyword followed by the value and a semicolon. Here is an example:

<script>
    function evaluateWeeklySalary() {
        var netPay = salary * time;

        return netPay;
    }
</script>

Introduction to Calling a Function that Returns a Value

To call a function that returns a value, you can assign its call to a local variable. Here is an example:

@{
    ViewBag.Title = "Salary Evaluation";
}

<h2>Salary Evaluation</h2>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td>Hourly Rate:</td>
            <td><input type="text" id="hourlyRate" /></td>
        </tr>
        <tr>
            <td>Time Worked:</td>
            <td><input type="text" class="timeWorked" /></td>
        </tr>
        <tr>
            <td>Net Pay:</td>
            <td><input type="text" id="netPay" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="button" value="Show Values" id="presentation" /></td>
        </tr>
    </table>
</form>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript" language="JavaScript">
    'use strict';

    var time = 44.00;
    var salary = 14.75;

    function evaluateWeeklySalary() {
        var netPay = salary * time;

        return netPay;
    }

    $(document).ready(function () {
        $("#presentation").click(function (event) {
            var weeklySalary;

            weeklySalary = evaluateWeeklySalary();

            $("#hourlyRate").val(salary);
            $(".timeWorked").val(time);
            $("#netPay").val(weeklySalary);
        });
    });
</script>

Techniques of Calling a Function that Returns a Value

You can call a function that returns a value as you do for one that doen't return a value. In the above code, we first declared a variable in one line and called the function in another line. This is done in case the values of the variable may change. Otherwise, you can declare the variable on the same line where you are calling the function. Here is an example:

<script>
    'use strict';
    
    var time = 44.00;
    var salary = 14.75;

    function evaluateWeeklySalary() {
        var netPay = salary * time;

        return netPay;
    }

    $(document).ready(function () {
        $("#presentation").click(function (event) {
            var weeklySalary = evaluateWeeklySalary();

            $("#hourlyRate").val(salary);
            $(".timeWorked").val(time);
            $("#netPay").val(weeklySalary);
        });
    });
</script>

In the previous two examples, we declared a variable to store the return value of the function. This is done if you plan to use the variable many times, or call the function many times, or if the value of the variable will change more than once. Here are examples:

@{
    ViewBag.Title = "Salary Evaluation";
}

<h2>Salary Evaluation</h2>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td>Hourly Rate:</td>
            <td><input type="text" id="hourlyRate" /></td>
        </tr>
    </table>
    <table>
        <tr>
            <td>Time Worked</td>
            <td>Week 1</td>
            <td>Week 2</td>
        </tr>
        <tr>
            <td>Monday</td>
            <td><input type="text" id="mondayWeek1" /></td>
            <td><input type="text" id="mondayWeek2" /></td>
        </tr>
        <tr>
            <td>Tuesday</td>
            <td><input type="text" id="tuesdayWeek1" /></td>
            <td><input type="text" id="tuesdayWeek2" /></td>
        </tr>
        <tr>
            <td>Wednesday</td>
            <td><input type="text" id="wednesdayWeek1" /></td>
            <td><input type="text" id="wednesdayWeek2" /></td>
        </tr>
        <tr>
            <td>Thursday</td>
            <td><input type="text" id="thursdayWeek1" /></td>
            <td><input type="text" id="thursdayWeek2" /></td>
        </tr>
        <tr>
            <td>Friday</td>
            <td><input type="text" id="fridayWeek1" /></td>
            <td><input type="text" id="fridayWeek2" /></td>
        </tr>
        <tr>
            <td>Time Worked:</td>
            <td><input type="text" id="timeWeek1" /></td>
            <td><input type="text" id="timeWeek2" /></td>
        </tr>
        <tr>
            <td>Weekly Salary:</td>
            <td><input type="text" id="weeklySalary1" /></td>
            <td><input type="text" id="weeklySalary2" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td style="text-align: right">Net Pay:</td>
            <td><input type="text" id="netPay" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td><input type="button" value="Show Values" name="evaluation" /></td>
        </tr>
    </table>
</form>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript" language="JavaScript">
    'use strict';

    var rate = 24.59;
    var mon1 = 8.00, tue1 = 10.50, wed1 = 9.00, thu1 = 8.50, fri1 = 8.00;
    var mon2 = 10.00, tue2 = 7.00, wed2 = 6.50, thu2 = 9.00, fri2 = 9.50;

    function calculateTime(day1, day2, day3, day4, day5) {
        var total = day1 + day2 + day3 + day4 + day5;

        return total;
    }

    function add(value1, value2) {
        return value1 + value2;
    }

    function multiply(value1, value2) {
        return value1 * value2;
    }

    $(document).ready(function () {
        $("#evaluation").click(function (event) {
            var week1Time = calculateTime(mon1, tue1, wed1, thu1, fri1);
            var week2Time = calculateTime(mon2, tue2, wed2, thu2, fri2);
            var week1Salary = multiply(rate, week1Time);
            var week2Salary = multiply(rate, week2Time);
            var netPay = week1Salary + week2Salary;

            $("#mondayWeek1").val(mon1);
            $("#tuesdayWeek1").val(tue1);
            $("#wednesdayWeek1").val(wed1);
            $("#thursdayWeek1").val(thu1);
            $("#fridayWeek1").val(fri1);

            $("#mondayWeek2").val(mon2);
            $("#tuesdayWeek2").val(tue2);
            $("#wednesdayWeek2").val(wed2);
            $("#thursdayWeek2").val(thu2);
            $("#fridayWeek2").val(fri2);

            $("#hourlyRate").val(rate);
            $("#timeWeek1").val(week1Time);
            $("#timeWeek2").val(week2Time);
            $("#weeklySalary1").val(week1Salary);
            $("#weeklySalary2").val(week2Salary);
            $("#netPay").val(netPay);
        });
    });
</script>

If you are planning to call the function once, or if you don't need to store its value in a variable, you can call the function directly where its value is needed. Here is an example:

. . . No Change

<script type="text/javascript">
    . . . No Change

    $(document).ready(function () {
        $("#evaluation").click(function (event) {
            var week1Salary = multiply(rate, calculateTime(mon1, tue1, wed1, thu1, fri1));
            var week2Salary = multiply(rate, calculateTime(mon2, tue2, wed2, thu2, fri2));
            var netPay = week1Salary + week2Salary;

            $("#mondayWeek1").val(mon1);
            $("#tuesdayWeek1").val(tue1);
            $("#wednesdayWeek1").val(wed1);
            $("#thursdayWeek1").val(thu1);
            $("#fridayWeek1").val(fri1);

            $("#mondayWeek2").val(mon2);
            $("#tuesdayWeek2").val(tue2);
            $("#wednesdayWeek2").val(wed2);
            $("#thursdayWeek2").val(thu2);
            $("#fridayWeek2").val(fri2);

            $("#hourlyRate").val(rate);
            $("#timeWeek1").val(calculateTime(mon1, tue1, wed1, thu1, fri1));
            $("#timeWeek2").val(calculateTime(mon2, tue2, wed2, thu2, fri2));
            $("#weeklySalary1").val(week1Salary);
            $("#weeklySalary2").val(week2Salary);
            $("#netPay").val(netPay);
        });
    });
</script>

Here is another version of the same code:

 . . . No Change

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript" language="JavaScript">
    . . . No Change

    $(document).ready(function () {
        $("#evaluation']").click(function (event) {
            var netPay = multiply(rate, calculateTime(mon1, tue1, wed1, thu1, fri1)) +
                         multiply(rate, calculateTime(mon2, tue2, wed2, thu2, fri2));

            $("#mondayWeek1").val(mon1);
            $("#tuesdayWeek1").val(tue1);
            $("#wednesdayWeek1").val(wed1);
            $("#thursdayWeek1").val(thu1);
            $("#fridayWeek1").val(fri1);

            $("#mondayWeek2").val(mon2);
            $("#tuesdayWeek2").val(tue2);
            $("#wednesdayWeek2").val(wed2);
            $("#thursdayWeek2").val(thu2);
            $("#fridayWeek2").val(fri2);

            $("#hourlyRate").val(rate);
            $("#timeWeek1").val(calculateTime(mon1, tue1, wed1, thu1, fri1));
            $("#timeWeek2").val(calculateTime(mon2, tue2, wed2, thu2, fri2));
            $("#weeklySalary1").val(multiply(rate, calculateTime(mon1, tue1, wed1, thu1, fri1)));
            $("#weeklySalary2").val(multiply(rate, calculateTime(mon2, tue2, wed2, thu2, fri2)));
            $("#netPay").val(netPay);
        });
    });
</script>

Nesting a Function

Introduction

Nesting a function is the ability to create a function in the body of another function.

Creating a Nested Function

To nest a function, in the body of an existing function, create a function using the function keyword, the parentheses, and a body delimited by curly brackets. The nested function doesn't need a name. Assign that nested function to a variable. In the body of the nested function, perform the operations you want. Here is an example:

<script>
    'use strict';
    var rate = 28.75;
    var work = 41.50;

    function present() {
        var calculate = function () {
            var total = rate * work;
        }
    }
</script>
</body>
</html>

When a function has been nested, it is hidden from outside its nesting (or parent) function. This means that the objects outside the nesting function cannot directly access the nested function and the outside functions cannot call it. Of course, the parent function can be called by anything in the script. If the nested function contains operations that other objects or functions may need, you can first call the nested function somewhere in the body of its parent function. After that, a call to its parent function would give access to the nested function. Here is an example:

@{
    ViewBag.Title = "Salary Evaluation";
}

<h2>Salary Evaluation</h2>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td>Hourly Rate:</td>
            <td><input type="text" id="hourlyRate" /></td>
        </tr>
        <tr>
            <td>Time Worked:</td>
            <td><input type="text" id="timeWorked" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="button" id="calculation" value="Calculate" /></td>
        </tr>
        <tr>
            <td>Total Salary:</td>
            <td><input type="text" id="totalSalary" /></td>
        </tr>
    </table>
</form>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript" language="JavaScript">
    'use strict';

    var rate = 28.75;
    var work = 41.50;

    $(document).ready(function () {
        $("input[id='calculation']").click(function (event) {
            var calculate = function () {
                var total = rate * work;

                $("#hourlyRate").val(rate);
                $("#timeWorked").val(work);
                $("#totalSalary").val(total);
            }

            calculate();
        });
    });
</script>

Passing Arguments to a Nested Function

You can create a nested function that uses one or more parameters. Create the function like any other. When you decide to call the nested function, remember to provide a value for each parameter.

Introduction to Built-In Functions

Introduction

To help you with the operations you need for your web projects, both JavaScript and jQuery provide many ready-made functions you can directly use.

Converting a Value to an Integer

To let you convert a value to a natural number, JavaScript provides a function named parseInt. Its syntax is:

int parseInt(string, radix);

This function takes one required argument and one optional argument. The requirement argument is the value that must be converted:

The second argument is valid only if the first one is, based on the above description. The second argument specifies the base by which the number will be converted. It is a number between 2 and 36. If you don't pass this argument, the number 10 would be used.

Converting a Value to a Floating-Point Number

To help you convert a value to a decimal number, JavaScript provides a function namedparseFloat. Its syntax is:

decimal parseFloat(value);

This function takes one argument as the value to be converted:

Normally, a floating-point number is made of two sections separated by the character designated by as the desimal separater. If the argument is a number like that, then the function will return it.

Anonymous Functions

Introduction

An anonymous function is a function that doesn't have a name. To create such a function, use the function keyword, the parentheses, and a body. If you will want to call that function, assign it to a locally declared variable. The formula to follow is:

var variable-name = function(){}

After defining the function, to call it, use the name of the variable and apply the parentheses to it.

Passing Arguments to an Anonymous Function

To pass an argument to an anonymous function, inside its parentheses, enter a name for the argument. In the body of the function, ignore or use the argument based on the value it has. When calling the function using the variable to which it was assigned, pass the appropriate value.

In the same way, you can create an anonymous function that takes as many arguments as you want. When calling the function, pass the argument in the right order based on their types.

Arrow Functions

JavaScript supports lambda expressions in what it calls arrow functions. An arrow function is a function that is defined where it is needed, as opposed to defining it in one place and calling it in another place.

An arrow function is created without a name, without the function keyword, and using the => operator between the parentheses and the curly brackets. Therefore, the primary formula of an arrow function is:

() => {. . .}

As seen with anonymous functions, if you plan to call the function, you can first assign it to a variable, and then use that variable to call the function.

Callback Functions

Callback Functions

A callback function is a function that is passed as argument to another function. The receiveing function B doesn't know and doesn't care how the argument function A works or what it does, but needs whatever behavior function A does so that function B can complete its work. In fact, function B doesn't check what function A does. At the right time, function B will need whatever it is supposed to get from function A. It is at that time that, if function A cannot produce the intended behavior or result, then function B may complain (or produce an error or an unreliable result). The topic of callback functions are not new. Callback functions probably get their origin in Assembly and/or C with the issue of pointers or function pointers.

Creating a Receiving Callback Function

In JavaScript, to create a function that takes a callback function as argument, simply provide a name for the argument (this is a little easier than in the other C-based functions where you must first define the callback function; we will see this issue with delegates in C#). Here is an example:

function receive(callback) {

}

At the time you judge it necessary, in the body of the function, apply the parentheses to the name of the argument to call the callback function. At that time, the receiving function will hand the processing to the callback function. This means that you must have defined the callback function. This would be done as follows:

function msgbox() {
    . . .
}

function receive(callback) {
    . . .

    callback();
            
    . . .
}

When calling the receving function, pass the name of a function that uses the same syntax as the argument. This would be done as follows:

function msgbox() {
    . . .
}

function receive(callback) {
    . . .

    callback();
            
    . . .
}

receive(msgbox);

A Callback Function with Arguments

A callback function can use one or more arguments. To start, create the function as normally as possible. When calling the callback function, pass the desired arguments to it.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2018-2022, FunctionX Next