maii
maii

Reputation: 49

switch case is always returning undefined

I am trying to make a switch case that returns random quotes from an array of facts/quotes and it's always giving me undefined although the switch case has no syntax errors

  let fact;
const rand=  Math.floor(Math.random() * 10);
console.log(rand)
switch(rand) {
  case 0:
    fact=facts[0]
    break;
  case 1:
      fact=facts[1]
    break;
  case 2:
     fact= facts[2]
      break;
  case 3:
     fact= facts[3]
      break;
  case 4:
     fact= facts[4]
      break;
  case 5:
     fact= facts[5]
      break;
  case 6:
      fact=facts[6]
      break;
  case 7:
      fact=facts[7]
      break;
  case 8:
     fact= facts[8]   
      break;
      default:
    fact = "dino random fact";

}

here I tried to log it to console:

    tile.classList.add("grid-item");
   tile.innerHTML=`<h3>${dinosaur.species}</h3>
                  
                   <p> ${console.log(fact)} </p>
                   <img src="images/${dinosaur.species}.png">
                  
                   `;

Upvotes: 1

Views: 537

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386654

You could take the random value as index and take the default as exceptional value.

const
    facts = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']
    rand = Math.floor(Math.random() * 10),
    fact = rand === 9
        ?  "dino random fact"
        : facts[rand];

console.log(fact);

Upvotes: 1

Ernesto
Ernesto

Reputation: 4272

facts does not exists so when you set fact = facts[something]

fact is undefined

Upvotes: 1

Related Questions