Sometimes I get "TypeError: [var] is undefined" even though it's defined in my code

Tell us what’s happening:

I am writing a script using jquery to randomly pull 5 entries from a list array, and sometimes when I click the button to generate the entries I get a console error “TypeError: eachCard is undefined” even though the variable eachCard is defined in the code.

Your code so far


$(document).ready(function(){
  
    //all possible cards and their point values
    var cardSource=[
      {
        card: "You remembered to do your homework",
        points:"5"
	    },
	    {
	    	card:"Dang that was funny!",
	    	points:"10"
	    },
      {
	    	card:"You got your rival in trouble",
	    	points:"20"
	    },
      {
	    	card:"You forgot to tie your shoelaces",
	    	points:"30"
	    },
      {
	    	card:"Quit playing with your food",
	    	points:"7"
	    },
      {
	    	card:"Rolled a brilliant success",
	    	points:"18"
	    },
	    {
	    	card:"Narrowly avoided expulsion",
	    	points:"25"
	    },
	    {
	    	card:"That was embarassing",
	    	points:"13"
	    }

	];
  
		$('#cardButton').click(function(evt){
      
			//prevent browser's default action
			evt.preventDefault();
      
      var randomCards = [] //an empty array to store our random card stack
      
      //fill it up!
      while(randomCards.length < 5){
          var sourceLength = cardSource.length;
          var randomNumber= Math.floor(Math.random()*sourceLength);
          var r = randomNumber + 1;
          if(randomCards.indexOf(r) === -1) randomCards.push(r);
      }
          
      var timeAnimation = 500;
      var cardContainer = $('#cardContainer');
      
      //fadeout on callback
      cardContainer.fadeOut(timeAnimation, function(){
        
        //make sure the stack is empty        
        $( "li" ).remove();
        
        
        //set a new stack of cards using the indices we picked in randomCards      
        $.each(randomCards, function(i, v) {
            var eachCard = cardSource[v];
            var cardStack = $('#cardStack');

            cardStack.append('<li><p class="cardValue">' + eachCard.card + '</p><p class="points">' + eachCard.points +' points</p>'+'</li>');
        });
        
        //fadein animation.
        cardContainer.fadeIn(timeAnimation);
      });  
      
			
      
      
	
      });//end cardButton function
});//end document ready

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:62.0) Gecko/20100101 Firefox/62.0.

My guess would be because of this:

var r = randomNumber + 1;

(in future post your code on codepen or jsfiddle)

Thank you for your reply! The forum will not let me post links because I am a new user, this demo is up at http:// broomstix-kauldronz. glitch. me/

Is there an error in the variable you’ve posted? Why would it be causing this problem only sometimes?

You’re generating an array of 5 random numbers. randomNumber will be between 0 and 6 (last index of cardSource). Then for some reason you’re adding 1 to randomNumber. And now the biggest number will be 7 - the index that doesn’t exist in cardSource.

Yes I understand what you mean now. I don’t remember why I included that now that I read the code more closely but you are correct that it doesn’t make sense. Once I remove the + 1 the page load successfully. Thank you for explaining!