Looking for a conceptual explanation of functions that provide new types of control flow

I am going through EloquentJS Chapter 5 High-Order Functions and have trouble understanding this concept of
"functions that provide new types of control flow." Please help me with this exercise:

function unless(test, then) {
if (!test) then();
}
function repeat(times, body) {
for (var i = 0; i < times; i++) body(i);
}

repeat(3, function(n) {
unless(n % 2, function() {
console.log(n, “is even”);
});
});
// → 0 is even
// → 2 is even

Hello,

I haven’t read this book, so I’ll try to help without knowing what you’ve already read or what the author has tried to communicate.

Control flow in programming is a general term used to describe things like for, if, and switch statements. We want the code to do one thing under certain conditions, and another thing under other conditions. I’m sure this is familiar to you by now.

if(thisIsTrue) {
  doThis();
}

That’s generally pretty readable. But what if we only want to run doThis() if thisIsTrue isn’t true? We have to add an exclamation mark, negating the truthiness of the condition.

if(!thisIsTrue) {
  doThis();
}

Again, programmers are pretty familiar with this, but it can be easy to miss that punctuation mark, and it also makes the code a little less readable. Is there a better way? What we want is to be able to read the code like this:

Unless thisIsTrue, run the function doThis()

We can do this in JavaScript because we’re allowed to do something that languages like C can’t do - we can pass functions to other functions:

function unless(test, then) {
  if (!test) then();
}

This code is pretty simple. You pass it a test value, test, and a function to run, then. If test is false, invoke test. These values can be anything we pass to unless(). Let’s call it.

unless( thisIsTrue, doThis );

Notice that doThis() doesn’t have the parentheses on it, which can be confusing. It doesn’t look like we’re passing a function. Just remember that you only use the parentheses on a function when you want to call it (I use them when naming functions in examples or explanations like this so we all know it’s a function). The upshot here is that we’ve created a new flow of control for JavaScript by passing a function to another function and letting it handle the logic.

I hope this helps. Apply the same logic to repeat(). What does it accomplish? Is it any more readable? Could you think of a way to make it more readable?

2 Likes