1

Why does the following returns undefined?

var global_vars = 
{

    countNumOfProperties : 
        function (obj) 
        {
            var count = 0;
            for (var k in obj) {
                if (obj.hasOwnProperty(k)) {
                    ++count;
                }
                return count;
            }
        }    
};


var DS =
{
    file_types_lookup : {}
};


global_vars.countNumOfProperties(DS.file_types_lookup)

4 Answers 4

2

Because the object has no own properties, so the for loop has no iterations that are executed, and no return statement gets executed.

I guess you misplaced a }:

var count = 0;
for (var k in obj) {
    if (obj.hasOwnProperty(k)) {
         ++count;
    }
}
return count;
Sign up to request clarification or add additional context in comments.

Comments

1

The return statement is inside the loop so is never reached.

        for (var k in obj) {
            if (obj.hasOwnProperty(k)) {
                ++count;
            }
            return count;
        }

should probably be

        for (var k in obj) {
            if (obj.hasOwnProperty(k)) {
                ++count;
            }
        }
        return count;

That way, each property will be checked before the sum is returned.

As written, the function will return

  • 1 to indicate that the first enumerable property is an own property, or
  • 0 to indicate that there are no own properties but there are enumerable inherited properties, or
  • undefined to indicate that there are no enumerable properties own or otherwise.

Comments

1

Observe what happens when you pass it an object that does have properties:

> global_vars.countNumOfProperties({foo: 1})
1
> global_vars.countNumOfProperties({foo: 1, bar: 2})
1
> global_vars.countNumOfProperties({foo: 1, bar: 2, baz: 3})
1

The problem is that you put the return statement inside the loop. It will be executed the first time the loop body executes, returning 1 and ending the loop. However, if the loop body never runs (because there are no properties) it never gets run and the function returns the default value, undefined.

You just need to move return down by one line, outside the loop.

Comments

1

The return count; statement should be outside of the for loop.

Comments

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.