Search code examples
javascriptarraysconditional-operator

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:

 const movieRating = rating.results;

 //Finding US ratings
 const findUSRating = movieRating.find((item) => item.iso_3166_1 === 'US');

//Filtering US ratings to remove null certifications. 
 const array = findUSRating.release_dates.filter((item) => item.certification);

//Ternary statement & where I am stuck.
console.log(array.length > 0 || array[index] !== undefined ? array[0].certification : `No certification Available For This Movie`);

Solution

  • 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 :

    const movieRating = [{
        iso_3166_1: 'Canada'
    }, {
        iso_3166_1: 'Australia'
    }];
    
     //Finding US ratings
     const findUSRating = movieRating.find((item) => item.iso_3166_1 === 'US');
    
    //Filtering US ratings to remove null certifications. 
     const array = findUSRating.release_dates.filter((item) => item.certification);
     
     console.log(array);

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

    Live Demo :

    const movieRating = [{
        iso_3166_1: 'US',
      release_dates: [{
        certification: 'A'
      }]
    }, {
        iso_3166_1: 'Australia',
      release_dates: [{
        certification: 'B'
      }]
    }];
    
     //Finding US ratings
     const findUSRating = movieRating?.find((item) => item.iso_3166_1 === 'US');
    
    //Filtering US ratings to remove null certifications. 
     const array = findUSRating?.release_dates.filter((item) => item.certification);
     
    console.log(array?.length > 0 || array !== undefined ? array[0].certification : `No certification Available For This Movie`);