javascript: why the return value is possible to be false

51 Views Asked by At
function test() {
    alert(1);
    return "hello";
}

Function.prototype.before = function (func) {
    var __bself = this;
    return function () {
        if (func.apply(this, arguments) == false)
            return false;

        return __bself.apply(__bself, arguments);
    }
};

test.before(function (){
    alert(2);
})();

What is the meaning of if (func.apply(this, arguments) == false)? I don't think the function will return false.

1

There are 1 best solutions below

0
On

Functions can return any value. That includes false.

If your functions don't return false then the code inside that conditional will never run. So you can remove it, if it annoys you for some reason.

Here is an example with a function which returns false:

function test() { // This function is never called
  console.log(1);
  return "hello";
}
Function.prototype.before = function (func) {
  var __bself = this;
  return function () {
    if (func.apply(this, arguments) == false){
      return false;
    }
    return __bself.apply(__bself, arguments);
  }
};
test.before(function (){
  console.log(2);
  return false;
})();