importerexporter
importerexporter

Reputation: 19

console.log not a function when passed as an argument to some other function and called within

I'm attempting to build my own for loop construct.

function loop(value, test, update, body) {
    if (test(value)) {
        body(value);
        return loop(update(value), test, update);
    }
}

The error the Edge browser is giving me:

VM1297:3 Uncaught TypeError: body is not a function
    at loop (<anonymous>:3:3)
    at loop (<anonymous>:4:10)
    at <anonymous>:1:1

Using this call:

loop(10, n => n > 0, n => n - 1, console.log)

Why does JS not see body as a function?

Upvotes: 0

Views: 28

Answers (1)

Nik
Nik

Reputation: 1709

You were not passing body as last parameter in next iteration. You should do loop(update(value), test, update, body); instead of loop(update(value), test, update);

function loop(value, test, update, body) {
  if (test(value)) {
    body(value);
    return loop(update(value), test, update, body);
  }
}

loop(10, n => n > 0, n => n - 1, console.log)

Upvotes: 1

Related Questions