skip to Main Content

please help me fix this code. For context, I was trying to create a randomiser that responds with ‘yes’ or ‘no’ etc to whatever question the user inputs. The main question is how do I return a random item in an array?

let yesOrNo = ['DEFINITELY!', 'yes', 'of course', 'hell no', 'no', 'absolutely not', 'maybe', 'probably']


const randomiser = (ques) => {

    if(typeof ques === 'string'){
      return Math.floor(Math.random() * yesOrNo.length); 
   } 
 }

console.log(randomiser('should i accept the company offer?'));
//output: 6

I want the code to return what’s written in the array but instead it returns the index num of the array items. For example, instead of ‘6’ I want it to return ‘maybe’.

I did come up with another way but it’s super messy and doesn’t seem productive at all.

const num = Math.floor(Math.random() * 7);

const randomiser = (ques) => {
  if(num === 0){
    return 'DEFINITELY!'
  } else if(num === 1){
    return 'yes'
  } else if(num === 2){
    return 'of course'
  } else if(num === 3){
    return 'hell no'
  } else if(num === 4){
    return 'no'
  } else if(num === 5){
    return 'absolutely not'
  } else if(num === 6){
    return 'maybe'
  } else if(num === 7){
    return 'probably'
  }
}

console.log(randomiser('should i accept the company offer?'));
//output: yes

I’m certainly open to new methods of achieving a randomiser if it’s more clean/efficient than mine.

2

Answers


  1. Just one small change:

    let yesOrNo = ['DEFINITELY!', 'yes', 'of course', 'hell no', 'no', 'absolutely not', 'maybe', 'probably'];
    const randomiser = (ques) => {
      if(typeof ques === 'string'){
        return yesOrNo[Math.floor(Math.random() * yesOrNo.length)]; 
     } 
    }
    console.log(randomiser('should i accept the company offer?'));
    
    Login or Signup to reply.
  2. As NgDaddy already answered, all that was missing was to access the array within your function.

    Just to add to the answer:

    // returns a random float in the range of 0 (inclusive) and 1 (exclusive) 
    Math.random() -> float
    

    This in combination with Math.floor ensures that Math.random() * array.length is always between 0 and array.length - 1.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search