[javascript] Javascript Uncaught TypeError: Cannot read property '0' of undefined

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

This question is related to javascript arrays error-handling typeerror

The answer is


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.


There is no error when I use your code,

but I am calling the hasLetter method like this:

hasLetter("a",words);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to error-handling

must declare a named package eclipse because this compilation unit is associated to the named module Error:Failed to open zip file. Gradle's dependency cache may be corrupt What does 'index 0 is out of bounds for axis 0 with size 0' mean? What's the source of Error: getaddrinfo EAI_AGAIN? Error handling with try and catch in Laravel What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean? Raise error in a Bash script Javascript Uncaught TypeError: Cannot read property '0' of undefined Multiple values in single-value context IndexError: too many indices for array

Examples related to typeerror

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this? Python TypeError must be str not int Uncaught TypeError: (intermediate value)(...) is not a function Slick Carousel Uncaught TypeError: $(...).slick is not a function Javascript Uncaught TypeError: Cannot read property '0' of undefined JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element' TypeError: 'list' object cannot be interpreted as an integer TypeError: unsupported operand type(s) for -: 'list' and 'list' I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer" Python sum() function with list parameter