Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set a custom start and end range in an array that displays a random string?

I am playing around with JavaScript while preparing for my junior developer interview.

I am trying to write a function that accepts two parameters, a beginning point and an ending point, in an array. This function should generate a random name within a custom start and end point of the array. I seemed close to getting it right, but it displays NaN. What is NaN?

Here is the code I wrote.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const names = ['Kitana', 'Liu Kang', 'Sonya Blade', 'Johnny Cage', 'Jax Briggs', 'Smoke', 'Sheeva', 'Jade']

const section = document.querySelector('section')

const para = document.createElement('p');

// Add your code here
function random(beginIndex, endIndex) {
  for (let beginIndex = 0; beginIndex < names.length; beginIndex = beginIndex + endIndex) {

    let newRangeOfIndices = names[beginIndex]

    const randomName = Math.floor(Math.random() * newRangeOfIndices)

    para.textContent = randomName
  }
}

random(2, 5)

// Don't edit the code below here!

section.innerHTML = ' ';

section.appendChild(para);
<section></section>

You will notice that I already set a custom limit in the function to be run, 2 to 5. But it’s still not working. Please help me out.

>Solution :

You don’t for loop to get a random number.

To get a random index.

let randomIndex = Math.floor(Math.random() * (endIndex - beginIndex + 1) + beginIndex)

Then get the random name from the names array.

let randomName = names[randomIndex]
const names = ['Kitana', 'Liu Kang', 'Sonya Blade', 'Johnny Cage', 'Jax Briggs', 'Smoke', 'Sheeva', 'Jade']

const section = document.querySelector('section')

const para = document.createElement('p');

// Add your code here
function random(beginIndex, endIndex) {
    let randomIndex = Math.floor(Math.random() * (endIndex - beginIndex + 1) + beginIndex)  
    let randomName = names[randomIndex]

    para.textContent = randomName
}

random(2, 5)

// Don't edit the code below here!

section.innerHTML = ' ';

section.appendChild(para);
<section></section>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading