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

3 Answers 3

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;
  ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

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 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.)
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

1 Comment

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

1 Comment

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."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.