how to tell if a javascript variable is a function

Mr Bell picture Mr Bell · May 2, 2011 · Viewed 33.4k times · Source

I need to loop over the properties of a javascript object. How can I tell if a property is a function or just a value?

var model =
{
    propertyA: 123,
    propertyB: function () { return 456; }
};

for (var property in model)
{
    var value;
    if(model[property] is function) //how can I tell if it is a function???
        value = model[property]();
    else 
        value = model[property];
}

Answer

Phrogz picture Phrogz · May 2, 2011

Use the typeof operator:

if (typeof model[property] == 'function') ...

Also, note that you should be sure that the properties you are iterating are part of this object, and not inherited as a public property on the prototype of some other object up the inheritance chain:

for (var property in model){
  if (!model.hasOwnProperty(property)) continue;
  ...
}