Doniyor Otamurodov
Doniyor Otamurodov

Reputation: 121

How to check if an element from props matches a condition?

Here I've made inCart condition which checks for the specific item existence in the cart but consequence is always true. What should I do instead? (second productId is already given)

      let inCart = () => {
        props.cart.forEach(product => {
          if (product.productId === productId) {
            return true;
          } else {
            return false;
          }
        });
      };
      inCart
        ? console.log("Was returned TRUE!")
        : console.log("Was returned FALSE!!!");

Upvotes: 0

Views: 286

Answers (3)

Alex Hughes
Alex Hughes

Reputation: 109

You're definitely missing the call, but also your function needs a slight edit.

You can't return a value within a forEach or map function - what you want to do is set a boolean variable, and then return that once you've iterated through the array.

const inCart = () => {
  let foundProduct = false;

  cart.forEach(product => {
    if (product.productId == productId) {
      foundProduct = true;
    }
  });

  return foundProduct;
};

    inCart()
        ? console.log("Was returned TRUE!")
        : console.log("Was returned FALSE!!!");

Upvotes: 0

Ioannis Potouridis
Ioannis Potouridis

Reputation: 1316

It returns true because inCart is defined but you don't call it.

If you call it, it returns undefined which is falsy. Try this instead.

let inCart = () => {
  return props.cart.some(product => product.productId === productId);
};

Upvotes: 3

Tim B James
Tim B James

Reputation: 20364

Looks like you are just missing executing your function inCart.

Change this to

inCart()
  ? console.log("Was returned TRUE!")
  : console.log("Was returned FALSE!!!");

Without executing the function, you are basically just saying "if I have a function"

Upvotes: 0

Related Questions