JavaScript if else problem

JavaScript if else problem
0

#1

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);
      

#2

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


#3

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


#4

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


#5

Anything like object not found


#6
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


#7

Thanks a lot @DanCouper


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