It may also be worth visiting my
Objects Page for more info as I talk about functions there as well.
...for instance, see Factory Functions for additional info.
The code for a function must be within a
<script type="text/javascript"> </script>
and can be either in the <head></head> or the bottom of the <body></body>
It is better to place it at the end of the BODY because when the web page gets loaded it will have to load
everything in the HEAD section before it displays the web page...but if it is at the end then the page will
load and be displayed before it loads the code for your FUNCTION(s).
NOTE...
Usually functions are used after some user interaction (maybe they click a button?) and this function
can go at the end...BUT...If your web page uses the functions while it loads, in order to display
the page properly, then it MUST go in the HEAD section otherwise the function will not be available
to be used.
***************
Also Note...
In more recent versions of JavaScript you can give parameters a default value when creating the function eg...
function myFunc(p1 = "Default Value") {
// Code
}
Therefore if you do not pass a value to the function when calling it it will
use "Default Value" as the passed in value.
***************
You can also use a shorthand way of creating the function that is assigned to a variable
(known as Arrow Functions)...eg...
const rectangleArea = myFunc(row, col) {
return "Area is: " + row*col;
}
Would be written in shorthand as...
const rectangleArea = (row, col) => {
return "Area is: " + row*col;
}
(It does not work too well when you include the this. command (see next pane))
And can be shortened still by...
A function assigned to a variable can be used in the following way(s):-
1.
Functions that take only a single parameter do not need that parameter to be enclosed
in parentheses. However, if a function takes zero or multiple parameters,
parentheses are required. Eg...
Zero parameters
const functionName = () => { return "Hello Gary" };
One parameter
const functionName = paramOne => { return "Hello Gary" };
Two or More parameters
const functionName = (paramOne, paramTwo) => { return "Hello Gary" };
2.
A function body composed of a single-line block does not need curly braces. Without the curly
braces, whatever that line evaluates will be automatically returned. The contents of the
block should immediately follow the arrow => and the return keyword can be
removed. This is referred to as implicit return.
Single Line Code Block
const functionName = paramOne => "ParamOne is:" + paramOne;
Examples...
<script type="text/javascript">
function myFunction1(p1, p2) {
return p1*p2;
}
</script>
This function may be called, for example, by the code...
var x = myFunction1(3, 4);
or
document.getElementById("myElement").innerHTML = "value is " + myFunction(3, 4);
This function was used to set the value of 'x' to be 12
and then changed the HTML code of an element with the ID of 'myElement' to be 'Value is 12'
***************
<script type="text/javascript">
function myFunction2(callElem, myVal) {
document.getElementById(callElem).value = myVal;
}
</script>
This function I used on my page (jsArrays and others) to display the value of the parameter 'myVal'
inside an INPUT BOX that had the ID name that was passed to it in the parameter 'callElem'.
***************
Stored as a variable...
var f1 = function(a, b) {return a * b;};
Then in your code you can say
z = f1(3, 4)
and z will then = 12
***************
I could even say...
var myObj = {
FName: "John",
LName:"Smith",
FULLName: function() {return this.FName + " " + this.LName}};
and this will use the function command to create the FULLName variable (myObj.FULLName).
NOTE...
this. is used to denote the properties (FName & LName) are within this object. If I refer
to FName & LName outside of creating this object (var myObj...) then I have to say
myObj.FName
So referring to myObj.FName will give me back the value of "John"
and myObj.LName will give "Smith"
and myObj.FULLName() will give "John Smith" - NOTE the brackets () - as it is a FUNCTION it MUST have
the brackets otherwise (myObj.FULLName) it will end up giving you the contents of your
function - a value of something like
ƒ () {return this.FName + " " + this.LName}
JavaScript functions behave like any other data type in the language;
we can assign functions to variables, and we can reassign them to new variables.
Because we can call the function name whatever we like it could end up
being a really long name (people like to assign names that describe what it does)
For Example...
function makeAnAnnouncementThatIAmVeryBusy() {
alert("I am very busy right now!");
}
You would not want to keep calling that long function name.
So you can assign it to a variable and then refer to the variable, eg...
const busy = makeAnAnnouncementThatIAmVeryBusy;
Then call it with the command
busy();
NOTE...
When assigning the function to a variable you DO NOT include the opening or closing brackets '()' BUT
you do need them when calling the variable.
If the function uses parameters you will not know the values when you assign it to a variable
only when you call the variable.
function makeAnAnnouncementThatIAmVeryBusy() {
alert("I am very busy right now!");
}
const busy = makeAnAnnouncementThatIAmVeryBusy;
Then call it with the command
busy();
The above will show an ALERT message saying
"I am very busy right now!"
OR...
function makeAnAnnouncementToShowHowBusyIAm(param1, param2) {
alert(param1 + ", I am " + param2 + " busy right now!");
}
const howBusy = makeAnAnnouncementToShowHowBusyIAm;
Then call it with the command
howBusy("Yes", "VERY");
The above will show an ALERT message saying
"Yes, I am VERY busy right now!"
NOTE ...
If you need to get the name of the function that is being used by 'howBusy' you could say...
console.log(howBusy.name);
and it will display "makeAnAnnouncementToShowHowBusyIAm" in the console log.
A higher-order function is a function that either accepts functions as parameters,
returns a function, or both!
I would normally create a variable (that is a function) in the following way...
const timeFuncRuntime = function(funcParameter) {
let t1 = Date.now();
funcParameter();
let t2 = Date.now();
return t2 - t1;
}
That tells me I want a variable called timeFuncRuntime
and it is a function that has one parameter (funcParameter)
And the task is between the { } brackets.
But the examples I am following uses the shorthand version (below)
which means the same...
const timeFuncRuntime = funcParameter => {
let t1 = Date.now();
funcParameter();
let t2 = Date.now();
return t2 - t1;
}
const addOneToOne = () => 1 + 1;
console.log(timeFuncRuntime(addOneToOne));
So...what is happening is :-
I am creating a variable called timeFuncRuntime
that is actually a function that requires one parameter (funcParameter)
The code inside the { }'s tell it to read in the date & time (t1) then run the function that was passed
to it as a parameter (funcParameter) then read in the date & time again (t2).
It then returns the difference (t2 - t1), which is probably the milliseconds it took to run
funcParameter.
addOneToOne is another function we created that justs returns the value of 1+1
The next line calls the function timeFuncRuntime and passed in the function we want to run
which was stored in the parameter funcParameter.
And an example of creating a factory function that returns
an object that has a mixture of properties & methods...
Note...Methods (eg mutate:) will create an anonymous function to return it's value
const myFactoryFunction = (number, array) => {
//Return a few different things at the same time
//...properties and methods
return {
specimenNum: number,
dna: array,
//Change 1 base DNA letter
mutate: () => {
var mutateArray = array;
var rnd = Math.floor(Math.random() * mutateArray.length);
var stop = 0;
var newBase = "";
do {
newBase = returnRandBase();
if (mutateArray[rnd] != newBase) {
mutateArray[rnd] = newBase;
stop = 1;
};
} while (stop = 0);
return mutateArray;
},
//Check percentage match of DNA
compareDNA: (pAequor) => {
var max = array.length;
if (max > pAequor.length) {
max = pAequor.length;
};
var match = 0;
var perc = 0;
for (i = 0; i < max; i++) {
if (array[i] == pAequor[i]) {
match++;
};
};
perc = Math.round((match / max) * 100);
return `specimen #1 and specimen #2 have ${perc}% DNA in common.`
},
//Return TRUE if 'G' or 'C' => 60% exists in DNA
willLikelySurvive: () => {
var countG = 0;
var countC = 0;
survive = false;
for (i = 0; i < array.length; i++) {
if (array[i] == "G") {
countG++;
} else if (array[i] == "C") {
countC++;
};
};
if (Math.round((countG / array.length) * 100) >= 60) {
survive = true;
} else if (Math.round((countC / array.length) * 100) >= 60) {
survive = true;
};
return survive;
}
};
//End of main RETURN
};
//End of myFactoryFunction
Depending on how you call a function is how your code reacts, for example...
Lets say you have a function, with no parameters in this example, created like this...
const myFunction = () => {
return "This is myFunction 1"
}
or it could be created like this...
function myFunction() {
return "This is myFunction 2"
}
When you call the function to actually be run you would say...
console.log(myFunction());
note the parentheses () are present.
But if you just need to reference the function and not run it yet you do not need the parentheses, eg...
setTimeout(myFunction, 2000);
note the parentheses () are NOT present as the timer is just referencing it now and will run it later.
If, using setTimeout and you need to pass parameters to the function then...
Lets say you have a function, with 2 parameters in this example...
function myFunction(param1, param2) {
return "This is myFunction 2 " + param1 + " " + param2;
}
With setTimeout you need to include the parameters on the end, like this...
setTimeout(myFunction, 2000, param1, param2);
note the parentheses () are still NOT present as the timer is just referencing it now and will run it later.