Javascript Uncaught TypeError: Cannot read property '0' of undefined

Greg Uptron picture Greg Uptron · Apr 3, 2015 · Viewed 115k times · Source

I know there's plenty of questions related to this error and I've checked most of them and none help me solve my issue. (Which seems so easy to debug...)

I have an array (which is empty aat first):

var words = [];

And my function hasLetter, checks if we find a letter (object) in the array (that I call here: d) words.

function hasLetter(letter,d){

// if words[0] not null should return object of letter "a", here we getting
// the index of the letter (since ascii of "a" is 97, I substract 97)
var ascii = letter.charCodeAt(0)-97;

//Trying to not get an error with this but still creates an err
if(typeof d[ascii ] !== "undefined" && d[ascii ] !== null && d[ascii ].length > 0){
    if(d[ascii].letter == letter){
        return true;
    }
}
return false; }

and I have a function called addLetter which checks if hasLetter returns true/false and then creates or not accordingly a new node.

function addLetter(letter,d){
var ascii = letter.charCodeAt(0)-97;
if(!hasLetter(letter,d)){
    document.write("This letter" + letter + " hasn't been found in words.");
    d[ascii] = new Node(letter);
}
    document.write("This letter " + letter + " already exists in words.");
    document.write(d[ascii].letter);

}

and if I test:

addLetter("a",words);

it returns:

Uncaught TypeError: Cannot read property '0' of undefined

I don't know what to do to say "if it's undefined then don't look into it or something along those lines...

Thanks

Answer

theonlygusti picture theonlygusti · Apr 3, 2015

The error is here:

hasLetter("a",words[]);

You are passing the first item of words, instead of the array.

Instead, pass the array to the function:

hasLetter("a",words);

Problem solved!


Here's a breakdown of what the problem was:

I'm guessing in your browser (chrome throws a different error), words[] == words[0], so when you call hasLetter("a",words[]);, you are actually calling hasLetter("a",words[0]);. So, in essence, you are passing the first item of words to your function, not the array as a whole.

Of course, because words is just an empty array, words[0] is undefined. Therefore, your function call is actually:

hasLetter("a", undefined);

which means that, when you try to access d[ascii], you are actually trying to access undefined[0], hence the error.