# How To Solve “TypeError: Cannot Read Property ‘0’ Of Undefined” In JavaScript

## The cause of this error

The main reason for the “TypeError: Cannot read property ‘0’ of undefined” in JavaScript error is a logic error in your code because you are not checking the variable first and trying to index into a variable (use []s on it) when the variable is undefined on array or string.

Before indexing into a variable, you can make sure that the variable supports indexing.

Example:

let myArray = []
let newArray = myArray[0];
console.log(newArray[0]);

Output:

The error will show if you try to run this code. An error occurs on line 3. Maybe you just meant “newArray”?

console.log(newArray[0]);
^
TypeError: Cannot read properties of undefined (reading '0')

## To Solve “TypeError: Cannot read Property ‘0’ of Undefined” in JavaScript

We’ve tested effectively with 3 solutions to solve this error by using an If statement, using optional chaining, and using conditional assignment. Reading to the end of the article to see how we solve this problem.

### Using an If statement

To avoid this error, you can use an if statement to check if your variable is undefined before you use it.

Example:

let myArray = []

// Use the if statement to make sure myArray is always defined
if (myArray) {
myArray[0] = ["LearnShareIT"];
}
else {
myArray = ["Learn", "Share", "IT"];
}

let newArray = myArray[0];
console.log(newArray[0]); 

Output

LearnShareIT

### Using Optional Chaining

Using the .? syntax, we can short circuit an attempt at accessing a property of an object if that object is undefined (of some other falsy value). By using this way, we can skip the rather verbose if/else method.

Example:

let myArray = []
let newArray = myArray?.newArray;
console.log(newArray);

// Conditional indexing, the .? syntax for myArray
myArray = { newArray: 'LearnShareIT' }

newArray = myArray?.newArray
console.log(newArray);

Output

undefined
LearnShareIT

### Using conditional assignment

The other simple way to solve this error is using conditional assignment by preventing the variable in question from being, well, undefined.

Example:

let myArray = undefined

// Using conditional assignment and assigning LearnShareIT element for myArray
let newArray = myArray ? myArray : "LearnShareIT";

console.log(newArray); 

Output

LearnShareIT

## Summary

In this article, we already explained to you how to solve the error “TypeError: Cannot read Property ‘0’ of Undefined” in JavaScript with three solutions using an if statement, using optional chaining, and using conditional assignment. We always hope this information will be of some help to you. If you have any questions, don’t hesitate and leave your comment below. Thank you for your read!

Maybe you are interested: