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