Anthony Eriksen
Anthony Eriksen

Reputation: 51

Intermittent type error when trying to split an array into an array of characters

So I have an array of "phrases" for a game show app project. I'm trying to generate a random number, to select a phrase within that array, then split the phrases characters.

When I return it with .split(), and call the function in the console, I get a type error, but it seems intermittent, if I call it several times, sometimes it works, others it throws a type error.

What seems to be the issue?

    const phrases = [
    'JavaScript is the best programming language',
    'I love CSS',
    'Check out Peer Reviews',
    'Stack Overflow',
    'This is in the phrases array'
    ];

    const getRandomPhraseAsArray = arr => {
    const randomNumber = arr[Math.floor(Math.random() * arr.length) +1];
    return randomNumber.split("");    
    };
app.js:22 Uncaught TypeError: Cannot read property 'split' of undefined
    at getRandomPhraseAsArray (app.js:22)
    at <anonymous>:1:1

Upvotes: 1

Views: 95

Answers (1)

Zeeshan Adil
Zeeshan Adil

Reputation: 2135

The problem with your code is that you are trying to add 1 to your Math.Random() This function gives a value between 0 to 1 and after you multiply whatever value it gives with the array length you are good to go but when you add +1 to it, It sometimes exceeds the array length. the proper fix should be:

  const phrases = [
    'JavaScript is the best programming language',
    'I love CSS',
    'Check out Peer Reviews',
    'Stack Overflow',
    'This is in the phrases array'
    ];

    const getRandomPhraseAsArray = arr => {
   //removed the +1 here
    const randomNumber = arr[Math.floor(Math.random() * arr.length)];
    return randomNumber.split("");    
    };

Hope this helps!

Upvotes: 1

Related Questions