Javascript - Random number


#1


https://www.codecademy.com/courses/learn-javascript/lessons/loops/exercises/while?action=lesson_resume&link_content_target=interstitial_lesson

How does the line var randomNumber=Math.floor(Math.random()*4); generate a number between 0 and 3? I dont see the upperlimit mentioned anywhere.


var cards=['Diamond', 'Spade', 'Heart', 'Club'];
var currentCard='Heart';
while(currentCard!=='Spade'){
  console.log(currentCard);
  
  var randomNumber=Math.floor(Math.random()*4);
  currentCard=cards[randomNumber];
}

console.log("Found a Spade!!!");


#2

Hi @makokam,

When you use Math.random() it generates a random number between 0 and 1. So when you times that by 4 you get a number between 0 and 4. You want to do this because there are 4 strings inside your cards array.

Let me know if you need anymore explanation.


#3

Hi @oscartbeamish

Thanks for the clarification. When you say between 0 and 4, it does not include 4 right?


#4

No it doesn't, try getting rid of all your code and put this in.

var randomNumber=Math.floor(Math.random()*4);
  

console.log(randomNumber);

Keep pressing run and you will get the idea.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.