TypeError: Cannot read property ‘length’ of undefined react

I am doing a simple exercise in React. The goal of the exercise is to simply:

  • Randomly draw fruit from the array
  • Log the message “I’d like one RANDOMFRUIT, please.”
  • Log the message “Here you go: RANDOMFRUIT”
  • Log the message “Delicious! May I have another?”
  • Remove the fruit from the array of fruits
  • Log the message “I’m sorry, we’re all out. We have FRUITSLEFT left.

While running this code, I’ve encountered the following error. For some reason, the “length” seems to be the problem.

TypeError: Cannot read property 'length' of undefined
Module../src/index.js
C:/Users/jaina/Desktop/ReactAPPS/exercise1/exercise-one/src/index.js:15
  12 | // Remove the fruit from the array of fruits
  13 | let remaining = remove(foods, fruit);
  14 | // Log the message “I’m sorry, we’re all out. We have FRUITSLEFT left.”
> 15 | console.log(`I’m sorry, we’re all out. We have ${remaining.length} other foods left.`);
  16 | 

It also says __webpack_require__ along with other webpack warnings. But I am assuming the main reason for not running is that “length” is undefined.

index.js

import foods from './foods';
import { choice, remove } from './helpers';

// Randomly draw a fruit from the array
let fruit = choice(foods);
// Log the message “I’d like one RANDOMFRUIT, please.”
console.log(`I’d like one ${fruit}, please.`);
// Log the message “Here you go: RANDOMFRUIT”
console.log(`Here you go: ${fruit}`);
// Log the message “Delicious! May I have another?”
console.log('Delicious! May I have another?');
// Remove the fruit from the array of fruits
let remaining = remove(foods, fruit);
// Log the message “I’m sorry, we’re all out. We have FRUITSLEFT left.”
console.log(`I’m sorry, we’re all out. We have ${remaining.length} other foods left.`);

Foods.js

const foods = [
    "🍇", "🍈", "🍉", "🍊", "🍋", "🍌", "🍍", "🍎",
    "🍏", "🍐", "🍒", "🍓", "🥝", "🍅", "🥑",
];

export default foods;

helper.js

function choice(items){
    let idx = Math.floor(Math.random()* items.length);
}

function remove(items, item){
    for (let i = 0; i < items.length; i++){
        if(items[i] === item){
            return [ ...items.slice(0,i), ...items.slice(i+1)];
        }
    }
}

export {choice, remove};

Any help is appreciated.

Answer

In helper.js, if your function remove does not find anything, it will return undefined. Then, when you say…

console.log(`I’m sorry, we’re all out. We have ${remaining.length} other foods left.`);

…you’re assuming remaining is an Array, but it’s actually undefined.

Try putting return items; at the end of the remove function, after the for loop.