JavaScript Functions Are Objects
It may surprise you but it’s right there in function’s definition:
The
Function
object provides methods for functions. In JavaScript, every function is actually aFunction
object.
An example
For example, functions can have properties, just like objects:
function hello(name) {
if (!hello.names) {
hello.names = new Set([name]);
} else {
hello.names.add(name);
}
return `Hello, ${name}!`;
}
hello('Sue');
hello('Beth');
hello('Tom');
console.log(hello.names); // {"Sue","Beth","Tom"}
Just because you can doesn’t mean you should
This is a neat party trick but I don’t think it’s a good idea.
Code clarity is everything and this pattern gets messy quickly. It is a fun trick though!
Deep dive
Checkout Kyle Simpson’s discussion of functions in his You Don’t Know JS series.