36

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];
}
Gordon Gustafson
  • 40,133
  • 25
  • 115
  • 157
Mr Bell
  • 9,228
  • 18
  • 84
  • 134
  • 1
    possible duplicate of [How can I check if a javascript variable is function type?](http://stackoverflow.com/questions/5999998/how-can-i-check-if-a-javascript-variable-is-function-type) – sierrasdetandil Nov 08 '13 at 01:03

3 Answers3

58

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;
  ...
}
Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • that is only reliable if the property is a native function. If it is a host object, you can get anything, even an error. – RobG May 03 '11 at 01:16
  • @RobG Oh? `typeof (new XMLHttpRequest).getAllResponseHeaders` returns `"function"` for me on Safari, Chrome, Firefox, and Opera. Is this an IE issue, or is there a different host object or method you're thinking of? (It's not that I doubt you, I'm just looking for an example.) – Phrogz May 03 '11 at 01:46
6

Following might be useful to you, I think.

How can I check if a javascript variable is function type?

BTW, I am using following to check for the function.

    // Test data
    var f1 = function () { alert("test"); }
    var o1 = { Name: "Object_1" };
    F_est = function () { };
    var o2 = new F_est();

    // Results
    alert(f1 instanceof Function); // true
    alert(o1 instanceof Function); // false
    alert(o2 instanceof Function); // false
Community
  • 1
  • 1
Kashyap
  • 107
  • 1
  • 5
  • 2
    Though unlikely, note that this will fail if you are testing a function value that came from another window frame (as each frame has its own `Function` root). – Phrogz Feb 03 '15 at 23:33
0

You can use the following solution to check if a JavaScript variable is a function:

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

for (var property in model)
{
    var value;
    if(typeof model[property] == 'function') // Like so!
    else 
        value = model[property];
}
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
Rintala
  • 51
  • 1
  • 6
  • 4
    Consider calling providing a little bit of written explanation for what you did apart from just the // Like so! comment. Maybe preface your code with a suggestion to "use the _typeof_ operator to determine the type of the property's value." – Wyck Aug 24 '18 at 19:58