JavaScript For/in loop malfunctioning - Issue with undefined object property bug

Currently, I am tackling a basic For/in loop exercise as part of a course curriculum I am enrolled in. The exercise involves working with a simple object containing 3 properties and creating a function that takes two parameters - the object name and the item to search for.

After writing my function and comparing it to the solution provided by the instructor, I realized they are identical. However, when testing it out in the console, an error is thrown indicating that the object property is not defined.

Here is the code snippet:

// 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`;
}

I would greatly appreciate any assistance from the community! Learning has been challenging but rewarding!

Thank you!

Answer №1

It seems like your code is functioning correctly for me, so the issue may lie in how you are calling the function or some hidden code.

By using an array instead of an object to store items, you can utilize array.find() or array.indexOf() to simplify basket manipulation.

// Question #2:
// Create a function checkBasket() to determine if the item is in the basket
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' ));

Answer №2

There is a small error in your code on the final line - instead of lookingfor, it should be written as lookingFor.

Answer №3

Recently reached this part of the lesson. The parameter needs to be a string data type. Give it a shot by inserting the code and then executing the function in this manner:

checkBasket(amazonBasket, 'books')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Response text from AJAX in PHP

I am working on an AJAX sign up form and I would like to incorporate a gear wheel animation similar to this When the server successfully signs up a user, I want a specific bar to change to green. To achieve this, I have echoed the names of the functions I ...

What are the reasons behind Jquery's decreased speed performance in Internet Explorer?

My ASP.NET page is quite intricate and heavily depends on jQuery for manipulating the DOM without using AJAX. Interestingly, I've observed that the page performs better in Mozilla browsers like Firefox compared to Internet Explorer 7 or 8. Could it b ...

looping through the iteration

Here is a link to my original plunker demonstration: http://plnkr.co/edit/9UBZ9E4uxAo1TXXghm1T?p=preview. In the case of div 4 (ng-if="show==4"), I am looking for a way to hide the particular div when the list is empty. Currently, each div is displayed fo ...

JavaScript code to place variables into an array with included variables

Looking for a solution: const myArray = [] myArray.push( { "bob" : { "banana" : "yellow" } }) console.log(myArray) Output: { "bob": { "banana": "yellow" } } Attempting a modifi ...

Transferring an image between two <td> cells within the same table

For a project, I'm working on creating a Checkers game. I have the checker board and pieces ready, but I'm struggling with the movement logic. My goal is to enable the image to move or transfer from one td element to another when clicked. A frie ...

When the object contains multiple arrays, filter out the id and remove it when clicked

I am working with an object that contains multiple arrays and aiming to filter out the id of the item to be removed onClick. However, I have encountered an error while trying to implement this logic. The error message I received is filter is not a functio ...

Maximizing the potential of mouse positioning in Angular

I am working with an Angular form that has a textarea <textarea class="form-control" id="message" formControlName="message" (fo ...

Unexpected behavior encountered in Rails app with unobtrusive JavaScript

I'm facing an issue with my link_to setup. Here's what I have: <%= link_to "Load More", comments_feed_path(@post.id), :id => 'my-link', :remote => true %> In my application.js file, I have the following code: $( document ...

There appears to be an issue with the v-model in the Vuetify v-btn-toggle

I have a situation where I am using two v-btn-toggles with multiple buttons in each. When selecting a button in the first toggle, it should impact which buttons are available in the second toggle based on a specific pattern: firstButtons: [ "a", "b", "c" ] ...

When utilizing webpack in Angular 5, the :host selector does not get converted into a component entity

Initially, I set up Angular with webpack following the configuration in this guide, including configuring webpack sass-loader. Everything was working smoothly until I encountered an issue today: app.component.ts @Component({ selector: 'ng-app&ap ...

What is the method for transmitting a YAML file in the form of a base64 encoded string?

I am attempting to transmit a yaml file as a base64 string in order for this code to function: const response = await octokit.request('GET /repos/{owner}/{repo}/git/blobs/{file_sha}', { owner: 'DevEx', repo: 'hpdev-content&apos ...

Error: Module not located - Unable to resolve 'crypto'

Upon running ng serve, I encountered a list of errors that need to be addressed. Here is my package JSON configuration: { "name": "ProName", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "tes ...

Transfer information from PHP to JavaScript across distinct files

In my website, I have several files including login.php, main.php, functions_js.js and functions_php.php. The login.php file retrieves two variables that I need to pass to the functions_php.php file via AJAX. In functions_php.php, I execute a SELECT query ...

Having issues transferring values from one page to another. Any suggestions to make it work correctly?

I currently have two pages within my website, one is called details.page and the other is maps.page. In the details page, I have set up a search input as shown below : <form method="get" id="form-search" data-ajax="true" action="maps.page"> ...

Nextjs version 13 encountered hydration failure due to discrepancies between the initial UI and the server-rendered content

I am currently utilizing the latest version 13.1.0. I have implemented a ContextProvider that allows switching between light and dark themes. 'use client'; import { Theme, ThemeContext } from '@store/theme'; import { ReactNode, useState ...

Click to switch CodeMirror's theme

http://jsbin.com/EzaKuXE/1/edit I've been attempting to switch the theme from default to cobalt and vice versa, toggling each time the button is clicked. However, I am facing an issue where it only switches to the new theme once and doesn't togg ...

Concealing the parent template in Vue Router when the child is displayed

Having some trouble setting up Vue.js with the router, specifically dealing with view display issues. I've created a router.js file with child routes for breadcrumbs and route clarity purposes. Each individual route loads perfectly fine when opened. ...

Is it possible to retrieve an array using axios?

Currently, I am exploring computed properties in Vue.js. One of the computed methods I am working on involves making a request to an axios API to retrieve an array after applying some logic within the promise. computed: { filteredTrips: function () { ...

Having trouble initiating an AJAX request

I'm currently facing an issue with inserting data into the database using AJAX. I have set up an ajax call to a servlet that is responsible for inserting data into the database. However, it seems like there might be an error in how I initialized the a ...

Angular state correctly maps to the controller but is not reflected in the HTML

I'm currently in the process of setting up a basic Angular application, something I've done many times before. I have defined a home state and another state for a note-taking app, but I am facing an issue where neither state is displaying or inje ...