Search code examples
javascriptfunctionobjecterror-handlingfor-in-loop

Javascript For/in loop not working - Object property is not defined Error


So i'm working on a simple For/in loop exercise from a course i am taking. We have a simple object with 3 properties and we have to create a function that takes 2 parameters - the object name and the item you're looking for.

I made my function and compared to the solution from the teacher and it's exactly the same. The problem is when i try it out in the console, i get an error that accuses the object property is not defined.

The code is as follows:

// Question #2:
// Write a function checkBasket() that lets you know if the item is in the basket or not
const amazonBasket = {
  glasses: 1,
  books: 2,
  floss: 100
}

function checkBasket(basket, lookingFor) {
  for(item in basket) {
    console.log(item);
     if(item === lookingFor) {
      return `${lookingFor} is in your basket`;
    }     
   }
   return `${lookingfor} is not in your basket`;
}

Would really appreciate any help guys! It's been a tough but enjoyable learning process!

Thanks!


Solution

  • Your code works as expected for me, so the issue is probably with how you call the function or something in code not shown.

    PS: If you use an array instead of an object to store the items, you can use array.find() or array.indexOf() and such to make manipulating the basket easier.

    // Question #2:
    // Write a function checkBasket() that lets you know if the item is in the basket or not
    const amazonBasket = {
      glasses: 1,
      books: 2,
      floss: 100
    }
    
    function checkBasket(basket, lookingFor) {
      for(item in basket) {
        console.log(item);
         if(item === lookingFor) {
          return `${lookingFor} is in your basket`;
        }     
       }
       return `${lookingFor} is not in your basket`;
    }
    
    console.log( checkBasket( amazonBasket, 'floss' ));
    console.log( checkBasket( amazonBasket, 'books' ));
    console.log( checkBasket( amazonBasket, 'glasses' ));

    const amazonBasket = [
      { "order_id": 1, "product_id": 13341544, "product_name": "glasses", "quantity": 1 },
      { "order_id": 1, "product_id": 12121321, "product_name": "books", "quantity": 5 },
      { "order_id": 1, "product_id": 47254114, "product_name": "floss", "quantity": 100 }
    ];
    
    const checkBasket = ( basket, lookingFor ) => {
      const item = basket.find( item => item.product_name === lookingFor );
      if ( item ) return `${lookingFor} is in your basket`;
      else return `${lookingFor} is not in your basket`;
    };
    
    console.log( checkBasket( amazonBasket, 'floss' ));
    console.log( checkBasket( amazonBasket, 'books' ));
    console.log( checkBasket( amazonBasket, 'glasses' ));