Skip to content
Advertisement

How do I check & return an error message if an array is undefined?

I am writing a ternary statement that prints out the certification of a movie (IE. PG, R…).

I am trying to return an error message that says “No Certification Available For This Movie” if the length of the array is equal to zero and if it is undefined. I managed to print the error message to the console if the array is equal to zero but I am struggling with printing an error message when it is undefined. I keep getting TypeError: Cannot read properties of undefined (reading 'release_dates') in the console.

This is what I have tried:

JavaScript

Advertisement

Answer

TypeError: Cannot read properties of undefined (reading ‘release_dates’)

As per the error, findUSRating is not defined. This error is coming as movieRating does not contain the object which is having iso_3166_1 as US.

Example :

JavaScript

To get rid from this, You can use Optional chaining (?.) operator.

Live Demo :

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement