Function Writing
We seem to have a problem here, so I am going to go back to this territory so you can get it down.
First, grammar. You have several ways of creating a function. Here are two very common ones.
function foo(args....)
{
}
foo = function(args....)
{
}
You can also create a "fat arrow" function like so.
(args...) =>
{
}
Second: purpose A function allows you to remember a procedure under a name and to supply inputs to the procedure. These inputs come in the form of a argument list which can have zero or more items in it. Functions can have an output, which comes in the form of a return value.
Some Case Studies
Let us look at an example. Let us produce a function
named greet
that puts Hello, name
too the console.
We would like to specify the name, so we will use it as an input. To to this, place it in the argument list. Our shell looks like this.
function greet(name)
{
console.log("Hello, " + name);
}
It is important to know that you can assume that the arguments
are defined and initalized varibles. Here is how you will get them
oin this case. We have one argument, name
. The caller
of your function will do something like this.
greet("Dan Teague");
In this case, the argument name
will be assiged
the string "Dan Teague"
.
You should feel free to treat the arguments of a function as already intialized variables.
This function has no return value. We can create a function with a similar purpose tht has a return value.
Here we will create a precondtion, which is something
that must be true when the function is called. In this case,
name
is a string.
The postconditions tell what a function does. This includes side-effects and describing any return value.
/*
* precondition: name is a string
* postcondition: returns the string "Hello, name!"
*/
function greetString(name)
{
return "Hello, " + name;
}
Let's compare this to our original greet
function.
Let's play with the law of cosines from math. If a triangle has sides of length \(a\) and \(b\) and an angle \(\theta)\) between the two sides, the length \(c\) of the third side is
$$c^2 = a^2 + b^2 - 2ab\cos(\theta).$$
/*
* preconditon: a and b are nonnegative numbers, and theta is an angle
* in radians.
* postcondition: returns the third side of a trangle with sides a and
* b and angle theta between them.
*/
function lawOfCosines(a, b, theta)
{
let cSquared = a*a + b*b - 2*a*b*Math.cos(theta);
return Math.sqrt(cSquared);
}
/*
* precondtions: s is a string, a is one-chaacter string.
* postconditions:
* returns s if a is not present in s and returns s truncted
* before a if a is present in s.
function chopper(s, a)
{
if( s.includes(a))
{
return s;
}
}