JavaScript if else problem

Problem in this is even the else part is getting printed
pls if anybody could resolve it.

var store = [{
			"productId": 1234,
      "weight": "115 Grams",
			"colour": "space grey"
			},
      {
			"productId": 12345,
			"weight": "120 Grams",
			"colour": "silver"
			}
  ]
  
  
var toReadData = function(store,id){
      
	for(i in store){
  	if(store[i].productId == id){
    	console.log("product id is "+ store[i].productId); 
     } else {
      console.log("No");
       }
   }
}

toReadData(store,12345);
      

You’re iterating over every item, so it should print two things as there are two things in the array. If you get rid of the else it will only print the found message if the item is found, otherwise it will do nothing

But if i want to add an else what should i do

What do you want the else to do? Return none of the item isn’t in the array?

Anything like object not found

var toReadData = function(store,id){
  for(item of store) {
    if (item.productId == id){
      return "product id is "+ item.productId;
    }
  }
  return "no item found";
};

Return returns from the function, so breaking the loop. No need for else, just run the loop: if nothing returns, loop is done and it goes onto “no item found”. Use console.log(toReadData(store, 1234)) to log if you want to log

Also just leaving the console logs as-is inside the function is fine, console.log doesn’t do anything

Thanks a lot @DanCouper

const toReadData = (store, id) => {
  const { productId } = store.find(x => x.productId === id)
  return productId ? `product id is ${productId}` : `no item found`
}