0

I have an array: this.entries = []. I run some code and it runs through this if statement several times:

if(this.entries[2] != null)

Everything works fine until after all the code runs I reset the array:

I've tried doing this.entries = [] and this.entries.splice(0, this.entries.length);

I re-run the code and when it gets to the if statement I get this error:

Cannot read property '2' of null

As far as I can tell there is nothing different. Tips and help would be very appreciated.

1
  • Can you post your whole function please? Commented Nov 24, 2011 at 17:36

1 Answer 1

4

There are several objects here. There is this which of course should never be null. Then there is this.entries Which is an array. Think of it as a container that can contain things. Then, there is this.entries[i] Which are the things in the container.

when this.entries[2] fails, it means that there is no object in slot 2 of the container.

However, the error Cannot read property '2' of null means that there IS NO CONTAINER. That is, the array itself has been set to null.

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

2 Comments

Javascript allows you to access an array out of bounds - it gives back undefined for reads and resizes the array for writes. There is no such thing as a "null error" in this case.
Thank you for the clarification. It seems I had accidentally set the entries to null somewhere else and that was what caused it to crash.

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.