0

I cannot for the life of me understand why I am getting the error:

"Type error: eCurVar is undefined". Please review the code below.

    var aBBTemplates = document.getElementsByClassName ("cBBTemplates");
    var i = 2;
    while (i < aBBTemplates.length)
    {
        var eCurVar = aBBTemplates[i];
        if (eCurVar === e.target)
        {
            eCurVar.style.zIndex = 3;
     // type error: eCurVar is undefined on the following line. 
        }   else if (eCurVar.style.zIndex === 3)    {
            console.log (eCurVar);
            eCurVar.style.zIndex = 3-1;
        }   else
        {
            console.log (eCurVar)
            eCurVar.style.zIndex = i;
        }
        i--;
    }

4 Answers 4

3

After each iteration i is decremented of one unit... and after three iterations it becomes negative; so you read aBBTemplates[-1] you get undefined.

When you can't understand what's going on with few console.logs, your best bet is to add a debugger; instruction, and open your devtool (usually by pressing F12).

As for your problem you could fix it by adding a check on i:

while (i < aBBTemplates.length && i >= 0) {
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that made perfect sense.
1

In the second case aBBTemplates[i] probably returns null

4 Comments

Are you implying that getElementsByClassName returns an array containing null ?
I'm implying that aBBTemplates[i], i.e. the item of the array at index i, evaluates to null.
@dystroy If you read OP's code, you'll see that he's * decrementing* i and at some point it will be -1. And aBBTemplates[-1] probably will be null. Thanks for the downvote anyway.
I've read that, that's why I upvoted bru's answer, that is the first answer to bring something more than just repeating the error message. Seriously, I would have suggested to comment instead of answering if you had said more than that...
1

You start with i equal to 2. Lets assume that aBBTemplates[2] returns something meaningful. You do someting with it and them decrement i. Lets assume aBBTemplates[1] in meaningful.

Keep going, and sooner or lates i becomes -1, which will definately not be meaningful when reading aBBTemplates[-1]

Comments

1

Into if function check if also eCurrVar is not a null

if (eCurVar != null && eCurVar === e.target){
// your code
} else {
// if ecurvar == null or ecurvar != e.targer
}

Also in while check if your i is possitive number, because array do not contains items with negative indexes:

while(i >= 0 && i < aBBTemplates.length)

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.