0
for ( var i=0; i<MyArrayObj.length; i++ ) {

}

I am getting an error called, Cannot call MyArrayObj, since its is NULL

1
  • Well, is it null? What's the problem here? Commented Aug 8, 2011 at 13:25

4 Answers 4

10

Assuming there isn't a logical error with MyArrayObj being null:

if(MyArrayObj) {
    for ( var i=0; i<MyArrayObj.length; i++ ) {

    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

That should be if( MyArrayObj ) without the bang.
Jeez, this received a lot of upvotes fast. @Matt Ball: I realized the mistake a few seconds after I typed it and edited it accordingly. It's early in the morning :)
if you want one-liner: for (var i=0; MyArrayObj && i<MyArrayObj.length; i++){...}
@John lol you're right.. better wait 5 minutes then any edit will appear in the post revision history. :)
3

You can also add this line above your loop just to be sure and avoid having to check at all:

MyArrayObj = MyArrayObj || [];

This will assign empty array into the variable in case it's null or undefined.

Comments

1

Did you declare the MyArrayObj and assigned a correct value to it?

Could you provide the code where you assign the array to a value?

Otherwise check if the array is not null first.

Comments

0

So that means you must not have initialized myArrayObj yet. You have to put something in the array before you can iterate through it.

1 Comment

True, but he can also check if it is null.

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.