Home > Enterprise >  TypeError TypeError: Cannot read properties of undefined (reading 'length') for Twitter bo
TypeError TypeError: Cannot read properties of undefined (reading 'length') for Twitter bo

Time:05-28

// function to generate a random tweet tweet
function ranDom (arr) {
  var index = Math.floor(Math.random()*arr.length);
  return arr[index];
};

This is the code used

CodePudding user response:

In general, you can add this line in the start of your function

if (arr === undefined){
    return DEFAULT_VALUE; \\define your default value for this case..
}

to handle this case.

But you need to investigate why your arr is undefined from the function call.

CodePudding user response:

Works fine here:

function ranDom (arr) {
  return arr[Math.floor(Math.random()*arr.length)];
};

var items = [254, 45, 212, 365, 2543];
console.log(ranDom(items));

  • Related