Function Tips
A function in a variable
Functions can be called in the normal way as we use them. We can also put a function into a variable. This can be done wit5h anonymous functions and with named functions.
The next lines show alert() which calls a variable that does not have a value but calls an anonymous function.
var test = function()
{
return "anonymous function executed";
}
alert(test());
The next lines perform the same action but here the function is a named function:
var testfunc = function test()
{
return "The function test is executed";
}
alert(testfunc());
The function test() is enclosed into the variable and can not be called seperately.
Call a function with a condition
Generally a function is called with a variable. It is also possible to call a function with a condition. Here is an example.
function test (tryme)
{
alert(tryme)
}
test(3>6)
The function test is called with (3>6). As this is false the alert will show "false"
test(3*16)
In this example the outcome is first calculated and then send to the function. The alert will therefore show 18.
Generally a function is called with a variable. It is also possible to call a function with a condition. Here is an example.
function test (tryme)
{
alert(tryme)
}
test(3>6)
The function test is called with (3>6). As this is false the alert will show "false"
test(3*16)
In this example the outcome is first calculated and then send to the function. The alert will therefore show 18.
Call a function with an unknown number arguments
Normally when we call a function we know how many arguments we pass.
For example:
var a=1, b="hello", c=3, d="world"
function(a, b, c, d)
It may happen that we call a function from several places in our script and we do not know upfront how many arguments we are going to pass. Then we can have the function itself examine how many arguments are passed:
function unknownnumber(a)
{
alert("first argument: " + a);
alert("number of arguments passed: " + arguments.length);
alert(arguments[3]);
}
var a=1, b="hello", c=3, d="world";
unknownnumber(a,b,c,d)
Arguments are passed to a function in an array. Using arguments.length we can examine how many arguments were passed and the arguments itself can be reached just like an array value using arguments[index].
Call a function with an unknown number arguments 2
The previous tip showed a method to call a function with an unknown number of parameters. There is another method. You can use rest.
function testfunction(...parameters)
{
alert(parameters);
}
testfunction(1, 2, 3, 4);
To ieterate through the parameters you can use the next snippet.
function testfunction(...parameters)
{
for(var value of parameters)
{
alert(value);
}
}
testfunction(1, 2, 3, 4, 5);
Call a function with default arguments
When you call a function it expects a certain number of arguments. When calling the function with to few arguments you can get faulty results. The next snippet shows how to predefine default values in a function which can be overruled during the function call.
function welcome(name, text="Hello ")
{
return text + name;
}
alert(welcome("Luc");
alert(welcome("Luc", "Good to see you "));
The first alert uses the name and the default value and returns: Hello Luc
The second alert uses both parameters and returns: Good to see you Luc
This works with calculations too:
function calculate(amount, times=2)
{
return amount * times;
}
alert(calculate(3));
alert(calculate(3,4));
Here the first alert uses the amount and the default value for times being 2 which results in 6.
The second alert uses both parameters and therefore returns 12.
Convert a string into a function
We can build a function from a string using the following method:
var myfunc = new Function (string)
Here is an example that demonstrates this.
var string = "alert('Hello World');"
var myfunc =new Function (string);
myfunc()
Be carefull with this. It is tempting to have an html input field in which someone can type a function and then execute this. This poses however a sincere security risk.
We can build a function from a string using the following method:
var myfunc = new Function (string)
Here is an example that demonstrates this.
var string = "alert('Hello World');"
var myfunc =new Function (string);
myfunc()
Be carefull with this. It is tempting to have an html input field in which someone can type a function and then execute this. This poses however a sincere security risk.
How to bypass a default parameter
A previous tip discussed how to use a function with default arguments. Here is how you can bypass one of the default arguments.
function myfunc(x, y=15, z=3)
{
console.log(x*y);
console.log(z);
}
myfunc(2,undefined,22)
In this example the console will show:
30
22
As the function is called with "undefined" as the second parameter that part of the function is not executed.
Repeat a function regularly
With setInterval(function, milliseconds) you can repeat a function on regular intervals. The most efficient thing to do is to put the functioncall into a variable. That way you can disable it with clearInterval. The next example activates a function every 5 seconds and places an alert on your screen. After 25 seconds the interval is disabled by the setTimeout() command.
<!DOCTYPE html>
<html>
<title>Repeat a function regularly</title>
<head>
<script>
var repeat = setInterval(often, 5000 );
var stoprepeat = setTimeout(stop, 25000);
function often()
{
alert("5 secs");
}
function stop()
{
clearInterval(repeat);
}
</script>
</head>
<body>
</body>
</html>
Repeat a function regularly x times
You can execute a function every x seconds or minutes. But what if you want to do that a predefined number of times. The next snippet shows how to do that.
for(var i = 0; i < 5; i++)
{
(function(xtimes)
{
setTimeout(function()
{
alert(xtimes);
}, xtimes*5000);
})(i);
}
The for loop decides how many times the function will get executed: in this example 5 times. The number 5000 tells the function to repeat every 5 seconds.
You can execute a function every x seconds or minutes. But what if you want to do that a predefined number of times. The next snippet shows how to do that.
for(var i = 0; i < 5; i++)
{
(function(xtimes)
{
setTimeout(function()
{
alert(xtimes);
}, xtimes*5000);
})(i);
}
The for loop decides how many times the function will get executed: in this example 5 times. The number 5000 tells the function to repeat every 5 seconds.
Stop a function in an interval
Generally a function performs a task and stops. There are however also functions that constant perform a certain task in the background. How to stop such a function is what we are going to show here. In a previous tip (Repeat a function regularly) I demonstrated how youn could stop a function after a certain time. Use setInterval for this and stopm the function with clearInterval. This can be done at a certain time interval but we can also do this by pushing a button.
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick = "start()">Start</button>
<button type="button" onclick = "stop()">Stop</button>
<p id="testid">======</p>
<script>
var timefunction = null;
var i=0;
function start() {
timefunction = setInterval(function()
{
i=i+1
document.getElementById("testid").innerHTML=i;
}, 1000);
}
function stop()
{
alert("The function is stopped")
clearInterval(timefunction);
}
</script>
</body>
</html>
In this example the function increases a number every second and puts it into a <p>. This is repeated until we press the"Stop" button.
Test if an argument is passed to a function
If a function should be called with multiple arguments but only one arguments is given the function might raise an error if any action is done on the missing argument. The next snippet shows how you can test if an argument is passed.
function func(arg1, arg2) {
if (typeof arg2 === "undefined") {
arg2 = "second arg not available";
}
alert(arg1+ " , "+ arg2)
}
func("Mancave")
If a function should be called with multiple arguments but only one arguments is given the function might raise an error if any action is done on the missing argument. The next snippet shows how you can test if an argument is passed.
function func(arg1, arg2) {
if (typeof arg2 === "undefined") {
arg2 = "second arg not available";
}
alert(arg1+ " , "+ arg2)
}
func("Mancave")
Warning if a parameter is forgotten in a function call
This tip gives some extra functionality to the earlier tip with the name: Call a function with default arguments. That tip shows how to pass a default value to a function when a parameter is omitted.
In stead of passing a standard value you can also pass a function. This allows to give a warning if a parameter is omitted. Here is an example.
function fault()
{
alert("Hey, fill it in !!");
return "Nobody";
};
function welcome(name = fault(), text="Hallo ")
{
return text + name;
}
alert(welcome());
alert(welcome("Luc", "Good to see you "));
If you call the function without the name the alert will show "Hey, fill it in !!" and the value "Nobody" is passed to the original function. You should take some action on that. It is possible to test for a faulty name in the original function (welcome), but using an extra function can keep things well-organised.