1

So I ran into this simple JavaScript code, and I'm surprised that objectA is being called as a function despite it not being defined as a function. why does objectA work when it's called as a function?

function greaterThan(x) {
  return function(y) {
    return y > x;
  };
}

var objectA = greaterThan(10);
console.log(objectA(9));

Here's the JSFiddle.

ayjay
  • 177
  • 1
  • 2
  • 7
  • 3
    `greaterThan` returns a function, which is assigned to `objectA`. What's unclear about that? – Rob W Oct 01 '13 at 17:08
  • Ah. So is this one way of "defining" a function (i.e., objectA is a function). I've never seen this kind of definition in other languages. – ayjay Oct 01 '13 at 17:11
  • 1
    Maybe this equivalent piece of code makes it somewhat clearer: http://jsfiddle.net/BUVC5/2/ – Rob W Oct 01 '13 at 17:12
  • Thanks, Rob. Yeah, that makes sense now. – ayjay Oct 01 '13 at 17:18
  • 1
    Yeah, you've never seen this in other languages because a lot of languages don't have [first-class functions](http://en.wikipedia.org/wiki/First-class_function). JavaScript is one of the languages that does, and it's one of the most awesome things about the language. – Nathan Wall Oct 02 '13 at 00:38

2 Answers2

2

You should know that, in JavaScript programming language, functions are first class citizen. This means that a function can be stored in a variable, array, or object. Also, a function can be passed to and returned from a function. And the last one behavior is what is happening here. You got a function when you call the greaterThan() function. A normal behavior here in JavaScript Codes.

See what happens if run this code:

alert(objectA instanceof Function);

For better understanding see the next code:

function greaterThan(x) {

       var result = function(y) {
            return y > x;
        };

       return result;

    }

What you get when you call the greaterThan function is just another function.

Another interesting matter in this code is related with how this new function maintains saved the value of x. This concept is called closures and you will see more here How do JavaScript closures work?.

Community
  • 1
  • 1
sergio
  • 619
  • 6
  • 16
1

Yeah, as @Rob said before, the function greaterThan returns another function, since javascript is a loosely typed language it has no restrictions on what a function returns.

So, based on that, the behavior is exactly as expected, you call a function which returns another function, store that new function into a variable, now that variable is a function itself...

Remember that Javascript is a dynamic language, it has no restrictions on data types and other stuff like normal languages (Java, C++, C#, etc).

Cheers.

Sam Ccp
  • 1,102
  • 3
  • 12
  • 19
  • higher-order-functions (i.e. functions that return functions) are not a feature of loosely typed languages, you can have them in statically/strongly typed languages as well. – Bergi Oct 01 '13 at 17:21