0

The working javascript snippet below does not include validation as it is only being used for learning purposes. However, I am not understanding the flow of events after variable 'isBetween' is defined within the buildBoundDetector() function. Why does passing a number through variable 'f' work?

function buildBoundDetector( lowerBound, upperBound ) {
    var isBetween = function(number){       
        if(lowerBound <= number && number <= upperBound){
            return true;
        }
        return false;
    }
    return isBetween;
}

var f = buildBoundDetector( 1, 100 );
f(45);
user1645914
  • 371
  • 6
  • 23
  • 2
    `return isBetween;`, it returns the function object. So, `f` is the `isBetween` function and you are actually passing `45` to `isBetween`. – thefourtheye Mar 01 '15 at 05:44
  • 2
    Time to learn about higher order functions: https://en.wikipedia.org/wiki/Higher-order_function – Felix Kling Mar 01 '15 at 05:57

2 Answers2

2

buildBoundDetector() is a function that returns a function. In Javascript, you can assign a function to a variable. That's what buildBoundDetector() does. It defines an anonymous function, then assigns it to isBetween, then returns isBetween. f is set to the result of buildBoundDetector(), which is that function. Because f is a function, you can call it.

KSFT
  • 1,774
  • 11
  • 17
1

In JavaScript, and many other languages, functions can be treated as values. So your first function returns a value which itself is a reference to a function. Then, the returned function value is applied, like any other function, to the argument 45.

amahfouz
  • 2,328
  • 2
  • 16
  • 21