difference between object and function in javascript

advertisements

This question already has an answer here:

  • javascript : function and object…? 7 answers

What is the exact difference between object and function in javascript when both are instanceof Object?

var obj = {};
function t(){}

console.log(obj instanceof Object); //true
console.log(t instanceof Object);   //true

console.log(typeof obj); //object
console.log(typeof t);   //function


A function is an object, which also has the ability to be called.

var obj = {};
function t(){}

console.log(obj instanceof Function); // false
console.log(t instanceof Function);   // true

t();   // Works
obj(); // Fails because you can't call non-functions (specifically,
       // the error is `TypeError: obj is not a function`

In JavaScript, all functions are objects (just like all Date objects are objects), and all objects are instanceof Object unless they're created with a null prototype:

function t(){}
var d = new Date();
console.log(t instanceof Object);                    // true
console.log(d instanceof Object);                    // true
var objWithNullPrototype = Object.create(null);
console.log(typeof objWithNullPrototype);            // "object"
console.log(objWithNullPrototype instanceof Object); // false

typeof is a very primitive operator, I'm afraid. It'll give you just "object" for most kinds of objects (Date, RegExp, Math), but for functions it goes that little bit further and tells you "function". I go into a bit of depth on typeof and its relatives in a post on my anemic little blog: Say what?