I'm using Pokeapi and want to display the types of the pokemon in 2 different element bc I'm applying a style (the background color) according to the type of the pokemon. The problem is that it shows the first 3 pokemon but not the fouth bc it has only one type and it can't find the second type (which doesn't exist) in the data given by the api.
Here's my JS :
function displayPokemon (pokemon) {
const pokemonEl = document.createElement('li');
const name = pokemon.name;
const type1 = pokemon.types[0].type.name;
const type2 = pokemon.types[1].type.name;
const pokemonHTMLString =
`
<div class="pokemon_container ${type1} ${type2}">
<div class="pokemon_container_image">
<img class="pokemon_container_image_sprite" src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemon.id}.png" loading="lazy" alt="${name}"/>
<img class="pokemon_container_image_shiny" src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/${pokemon.id}.png" loading="lazy" alt="${name}"/>
</div>
<h3 class="pokemon_number">#${pokemon.id.toString().padStart(3, '0')}</h3>
<h2 class="pokemon_name" onClick = "selectPokemon(${pokemon.id})">${name}</h2>
<a class="pokemon_type" id="${type1}">
<img id="${type1}" alt="${type1}"></img>
<span>${type1}</span>
</a>
<a class="pokemon_type" id="${type2}">
<img id="${type2}" alt="${type2}"></img>
<span>${type2}</span>
</a>
</div>
`
pokemonEl.innerHTML = pokemonHTMLString;
pokedex.appendChild(pokemonEl);
};
Here's the error : "Uncaught (in promise) TypeError: pokemon.types[1] is undefined"
Before that I was mapping the types and showing them in one element but I want to do 2 separate elements and I don't know if my code is wrong and I have to modify something or if I have to create a function or an if else statement.
You should check for "nullability" of the second optional type (variable) and react to that scenario (no second type) to avoid this kind of errors where you depend on something which does not exist. The simplest way, in this case, would be to use if-else statements to change the displayed HTML.