B T
B T

Reputation: 161

Using typeof to check for object properties not working

I have an object that I need to check the properties to see if they are all strings and if so return true, but mine always returns true.

function StringsObj(x) {
        for (var prop in x) {
            if(typeof x[prop] === "string") {
                return true;
                }
            else {
                return false;
            }

        }
    } 

var student = {
        name: "Judy",
        class: "freshman",
        age: 19,
        honors: true
    };

StringsObj(student)

Upvotes: 1

Views: 2984

Answers (1)

potashin
potashin

Reputation: 44581

It happens because after the first check you function returns true ("Judy" is of string type) and stops executing. You can do something like this :

function StringsObj(x) {
    for (var prop in x) {
        if(typeof x[prop] !== "string") {
            return false;
        }
    }
    return true;
} 

JSFiddle

Upvotes: 2

Related Questions