Michael Comes Michael Comes - 4 months ago 7
Javascript Question

JavaScript 'undefined'

sort of an easy one. Can you help me in explaining why the line the
"console.log("test", nn) })", is showing nn as undefined rather than the value 3? Thank you much. Here is the code snippet.

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

repeat(3, function(n) {
var nn = unless(n % 2, function() {
return 1 * 3
});
console.log("test", nn)
});

Answer

Your unless() function does not return anything. Thus

var nn = unless(...);

means that nn will just be undefined. For nn to have a value, your unless() function must return a value.

In here:

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

There is no return statement. The callback then() might return a value, but that just makes that value available within unless() if you assigned it to something. If you want unless() itself to return a value, you need to add one or more appropriate return statements.

For example, you could fix part of the problem by just returning the then() value such as:

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

But, you still need a return value for the case where test is truthy. I'm not sure what you want that return value to be in that case so I don't know what to recommend, but the general form could be this:

function unless(test, then) {
  if (!test) {
      return then();
  } else {
      return somethingelse;   // assign some return value when `test` is truthy
  }
}