Z_Cason
Z_Cason

Reputation: 25

iterating through an array using loops and if else statements

I'm trying to compare the name to the item names in the list and return the price of that item but it's not going through the full list. Can someone explain to me what I'm doing wrong and how to correct it?

let items = [
  {
    itemName: "Effective Programming Habits",
    type: "book",
    price: 13.99
  },
  {
    itemName: "Creation 3005",
    type: "computer",
    price: 299.99
  },
  {
    itemName: "Finding Your Center",
    type: "book",
    price: 15.00
  }

]function priceLookup (itemsList, name) {
  let price = null;
  for (item of itemsList) {
    if (item.itemName === name) {
      price = item.price;
    }
    else { price = "No item found with that name";
    }
  }
  return price;
}

Upvotes: 0

Views: 70

Answers (2)

Shivanshu Gupta
Shivanshu Gupta

Reputation: 324

It's happening because you have reassigned price in else to ""No item found with that name". Possible Solution:

function priceLookup (itemsList, name) {
  let price = "No item found with that name";
  for (item of itemsList) {
    if (item.itemName === name) {
      price = item.price;
      break;
    }
  }
  return price;
}

Upvotes: 1

Jacob
Jacob

Reputation: 78920

It is going through the full list, and that's the problem. Notice that if the if branch is hit, price gets populated, but the next time around in the loop, the else branch may take place, so price will be overwritten with that string.

You can use break to stop looping in your if branch once you've found the match, or use the find method of the Array instead.

function priceLookup (itemsList, name) {
  const price = itemsList.find(item => item.itemName === name);
  return price ?? "No item found with that name";
}

Upvotes: 2

Related Questions