2

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
CodingGorilla
  • 19,612
  • 4
  • 45
  • 65

2 Answers2

5

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?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

In Javascript we consider function as objects that we call in our program.Objects is not function you assume like this object is parent and every functions are child of object.

var speak = function(what){
    console.log(this);

}

speak("woof");

function test(){
    var a=1;
}
Wasiq Muhammad
  • 3,080
  • 3
  • 16
  • 29