Characteristics of Functions
Characteristics of Functions
Anonymous Functions
Introduction
A function is said to be anonymous if it returns a value but it doesn't have a name. If may appear as follows:
function( . . . ){ return . . . }
Practical Learning: Introducing Anonymous Functions
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; }
using System.Web.Optimization;
namespace PayrollPreparation3
{
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"));
}
}
}
using System.Web.Mvc;
namespace PayrollPreparation1.Controllers
{
public class HomeController : Controller
{
. . .
public ActionResult PayrollEvaluation() => View();
}
}
@{ 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"> </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> </td> <td> </td> <td> </td> <td> </td> <td class="bold">Weekly Salary:</td> <td><span id="weeklySalary"></span></td> </tr> </table> </div>
Creating an Anonymous Function
There are various ways to create an anonymous function. As one way, in JavaScript, assign the creation of the anonymous function to a variable. Here is an example:
let price = function () { return 97.82; }
If the function needs a parameter, write that parameter in the parentheses of the anonymous function. In the same way, you can create an anonymous function that uses as many parameters as you want. In the body of the function, you can ignore or use the parameter(s). Here is an example:
let multiplication = function (x, y) { return x * y; }
In TypeScript, it may be a good idea to specify the data type of a(each) parameter. Here are examples:
let multiplication = function (x: number, y: number) { return x * y; }
If you are assigning the anonymous function to a variable, you an also specify the data type of that variable. Here is an example:
let multiplication: number = function (x: number, y: number) { return x * y; }
Calling an Anonymous Function
If you had created an anonymous function by assigning it to a variable, the variable becomes the name of the function. Based on this, to call the function, use the name of the variable and the parentheses the same way you call a function as we saw earlier.
Practical Learning: Creating and Using an Anonymous Function
function evaluateDailySalary(day: string, salary: number, time: number) {
let pay = function (x, y) { return x * y; }
document.querySelector(day).innerHTML = pay(salary, time).toFixed(2);
}
function calculate() {
const hSalary: number = 19.84;
const mon: number = 5.50;
const tue: number = 7.00;
const wed: number = 8.50;
const thu: number = 7.50;
const fri: number = 6.00;
let multiplication = function (x: number, y: number) { return x * y; }
let addition = function (a: number, b: number, c: number, d: number, e: number) { return a + b + c + d + e; }
const weeklySalary: number = multiplication(addition(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();
@{
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"> </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> </td>
<td> </td>
<td> </td>
<td> </td>
<td class="bold">Weekly Salary:</td>
<td><span id="weeklySalary"></span></td>
</tr>
</table>
</div>
<script src="~/Scripts/TimeSheetEvaluation.js"></script>
The Return Type of an Anonymous Function
When creating an anomymous function, if you want, you can specify the type of the return value. To do that, after the variable, type a colon followed by parentheses. In the parentheses, enter the same number of parameters as the anonymous function. After the parentheses, type => followed by the return type of the anonymous function.
Contextual Typing
When specifying the data type(s) of the parameter(s) of the return type of a function, you can omit or specify the data types of the parameters. You have four options:
let multiplication: (x, y) => number = function (x, y) { return x * y; }
let multiplication: (x: number, y: number) => number = function (x, y) { return x * y; }
let multiplication: (x, y) => number = function (x: number, y: number) { return x * y; }
Practical Learning: Setting the Type of an Anonymous Function
function evaluateDailySalary(day: string, salary: number, time: number) { let pay = function (x, y) { return x * y; } document.querySelector(day).innerHTML = pay(salary, time).toFixed(2); } function calculate() { const hSalary: number = 32.79; const mon: number = 9.00; const tue: number = 10.00; const wed: number = 9.00; const thu: number = 8.50; const fri: number = 8.00; let multiplication: (x: number, y: number) => number = function (x: number, y: number) { return x * y; } let addition: (a: number, b: number, c: number, d: number, e: number) => number = function (a: number, b: number, c: number, d: number, e: number) { return a + b + c + d + e; } const weeklySalary: number = multiplication(addition(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();
Arrow Functions
Introduction
An arrow function is an alternative to an anonymous function. This means that an arrow function is another technique to create a short nested function. This time, the anonymous function doesn't use the function keyword.
Creating an Arrow Function
To get an arrow function, create an anonymous function without the function keyword. You can assign the function to a variable. Here is an example:
let price = () => { return 145.85; }
If you are assigning the function to a variable, you can specify the data type of that variable. Here is an example:
let price: number = () => { return 145.85; }
You can then call the function the same way we saw for an anonymous function, using the name of the variable. Here is an example:
View: CompanyInventory.cshtml
@{ ViewBag.Title = "Store Inventory"; } <h2>Store Inventory</h2> <p id="markedPrice"></p> <script src="~/Scripts/BusinessManagement.js"></script>
TypeScript File: BusinessManagement.ts
let price: number = () => { return 145.85; } document.querySelector("#markedPrice").innerHTML = price().toFixed(2);
A Parameterized Lambda Expression
Like a regular function, an arrow function can use one or more parameters. If the expression must use a parameter, write at least the name of the parameter in the parentheses. As always, in the body of the function, you can ignore or use the parameter. When calling the expression, pass an appropriate argument. Here is an example:
let price: number = (discount) => { return 145.85 - (145.85 * discount / 100); } document.querySelector("#markedPrice").innerHTML = price(20).toFixed(2);
If you want, you can specify the data type of the parameter. Here is an example:
let price: number = (discount: number) => { return 145.85 - (145.85 * discount / 100); }
In the same way, you can create an arrow function that uses as many parameters as you need (of course, the parameters can be of different types). When calling the function, make sure the pass the exact number and type(s) of argument. Here is an example:
let price: number = (original, discount) => { return original - (original * discount / 100); } let markedPrice = price(188.85, 35); document.querySelector("#markedPrice").innerHTML = markedPrice.toFixed(2);
Once again, you can optionally specify the data types of the parameters. Here are examples:
let price: string = (itemName: string, original: number, category: string, discount: number) => { return category + " " + itemName + ", original price: " + original.toFixed(2) + " discounted at " + discount + "%. " + "Current Market Price: " + (original - (original * discount / 100)).toFixed(2); } let markedPrice: number = price("Blue Dress", 188.85, 'Female', 35); document.querySelector("#markedPrice").innerHTML = markedPrice;
Nesting a Function
Introduction
In JavaScript and thererfore TypeScript, you can create a function in the body of another function. This is referred to as nesting a function.
Creating a Nested Function
To create a nested a function, in the body of the nesting function, create a function following the same rules we have applied so far. Here is an example:
function presentation() {
document.querySelector("#companyName").innerHTML = "Bethesda Car Rental";
function introduction() {
}
}
presentation();
A nested function is available only in the body of its nesting (or parent) function. Therefore, to use a nested function, call it inside the nesting function but outside the nesting function. Normally, you can call the nested function before or after its body. Here is an example:
function presentation() {
introduction();
document.querySelector("#companyName").innerHTML = "Bethesda Car Rental";
function introduction() {
document.querySelector("#introduction").innerHTML = "Welcome to our one-stop car rental management";
}
}
presentation();
In an existing function, you can nest as many functions as you want. You can also nest a function in another function that itself is nested. The main rule is that a nested function call be accessed only in the body of its nesting function.
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.
Default Arguments
Introduction
When you call a function that uses a parameter, you must pass an appropriate argument based on the type of the parameter. If you happen to pass the same argument almost everytime you call the function, you can create the function and provide that value as default. You have various options.
A Default Value for a Parameter
When creating a function that uses a parameter, if you want to provide a default value for the parameter, assign that value to the parameter. Here is an example:
function categorize(type = "Female") {
}
If you want, you can specify the data type of the parameter. Here is an example:
function categorize(type: string = "Female") {
}
Once again, in the body of the function, you can ignore or use the parameter. When calling the function, you can provide a value for the parameter. Here is an example:
function categorize(type = "Female") {
document.querySelector("#category").innerHTML = type;
}
categorize('Baby Girl');
Otherwise, when a parameter has a default value, you can omit passing an argument. Here is an example:
function categorize(type = "Female") {
document.querySelector("#category").innerHTML = type;
}
categorize();
If you omit the argument, the default value would be used for the parameter when the function is called.
An Undefined Optional Argument
When creating a function that uses a parameter, you may not want the argument to be required but at the same time, you may not want to provide a specific value for the parameter. In this case, you can let the compiler know that the default value is unknwon. To do this, on the right side of the parameter, type a question mark. Here is an example:
function categorize(type?) {
document.querySelector("#category").innerHTML = type;
}
categorize();
If you want to specify the data type of the parameter, write it after the question mark. Here is an example:
function categorize(type?: string) {
document.querySelector("#category").innerHTML = type;
}
categorize();
Either way, when you call the function, you can pass argument to it. If you omit the argument, the compiler would set its value to undefined.
A Function with some Detault Arguments
You can create a function that uses more than one parameter where one or more parameters have default values and one or more parameters are required. If you are creating a function that uses two parameter with one required and one with a default value, the parameter that has a default value must come second. Here is an example:
function calculateDiscountAmount(price, discount = 0.00) {
return price - (price * discount / 100);
}
Of course, you can specify the data types of the parameter. When calling the function, you cass only the required argument. Here is an example:
View: StoreInventory.cshtml
@{ ViewBag.Title = "Store Inventory"; } <h2>Store Inventory</h2> <p class="netPrice"></p> <script src="~/Scripts/Evaluations.js"></script>
TypeScript File: Evaluations.ts
function calculateDiscountAmount(price: number, discount: number = 0.00) {
let markedPrice: number = price - (price * discount / 100);
document.querySelector(".netPrice").innerHTML = markedPrice.toFixed(2);
}
calculateDiscountAmount(325, 25);
You can also pass both arguments. If you are creating a function that uses more than two parameters and one of those parameters will use a default value, the parameter with the default value must be the last. When calling the function, you can pass all arguments or omit the last one. Here is an example:
function calculateDiscountAmount(price: number, itemName: string, discount: number = 25) { let markedPrice: number = price - (price * discount / 100); document.querySelector(".netPrice").innerHTML = itemName + " selling for " + markedPrice.toFixed(2); } calculateDiscountAmount(86.45, "Khaki Striped Dress");
If you are creating a function that uses more than two parameters and some of the parameters use default values, the parameters with default values must come last. When calling the function, you must pass all required arguments in their order. You can pass or omit the last argument(s).
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 is 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). 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 Learning: Ending the Lesson
|
||
Previous | Copyright © 2018-2019, FunctionX | Next |
|