Is Function in JavaScript an Object?

Find out if JavaScript functions are objects

JavaScript has primitive data types and objects. Every function in JavaScript is in fact an object — it is an instance of the Function constructor. You can see this with the following code:

// function declaration/statement
(function foo(){}).constructor === Function; // true
// anonymous function
(function(){}).constructor === Function; // true
// function expression
const expr = function() {};
expr.constructor === Function; // true
// arrow function
(() => {}).constructor === Function; // true

The context bounded to functions could be different depending on how you define a function.

The difference between a Function object and other objects in JavaScript is the fact that functions can be invoked/called directly (without creating a new constructor instance):

function foo() {
    console.log('called');
}

console.log(foo()); // 'called'

Like other objects, functions can have properties and methods, and they can be instantiated (when the constructor is called with the new keyword):

function Foo(prop) {
    this.prop = prop;

    this.method = function() {
        console.log('foo');
    }
}

const foo = new Foo('bar');

console.log(foo.prop); // 'bar'
console.log(foo.method()); // 'foo'

Hope you found this post useful. It was published . Please show your love and support by sharing this post.