Search code examples
javascripttypeof

how to tell if a javascript variable is a function


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];
}

Solution

  • 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;
      ...
    }