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);
2
  • 2
    return isBetween;, it returns the function object. So, f is the isBetween function and you are actually passing 45 to isBetween. Commented Mar 1, 2015 at 5:44
  • 2
    Time to learn about higher order functions: en.wikipedia.org/wiki/Higher-order_function Commented Mar 1, 2015 at 5:57

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.