Weird Tricks with Functions

Functions are so special in JavaScript that you can do all sorts of crazy things to them. Whole books have been written on “functional” JavaScript, but let’s take a look at one trick that we will use later.

Recursion

Change the hello like this:

 
function​ hello(name) {
 
var​ ret = ​'Hello, '​ + name + ​'! '​ + ​'You look very pretty today :)'​;
 
if​ (!name.match(/again/)) {
​ 
ret = ret + ​' /// '​ + hello(name + ​' (again)'​);
 
}
 
return​ ret;
 
}

Look closely here. Inside the body of the function hello, we’re calling the function hello!

This will log the hello messages twice.

images/functions/hello_hello.png

A function that calls itself ...

Get 3D Game Programming for Kids now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.