Reputation: 177
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.
Upvotes: 1
Views: 98
Reputation: 639
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?.
Upvotes: 2
Reputation: 1162
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.
Upvotes: 1