1

I have the following condition.

if (!product.tag_id) {
  return;
}

How can I change it in a way that for the tag_id which is equal to 0 it will not return wrong thing. Now it considers tag_id:0 as false value and returns nothing. How can be it fixed?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
NewTech Lover
  • 1,185
  • 4
  • 20
  • 44
  • 2
    You should test for the specific `false` value with `===`. Or if you want to know if there's a `tag_id` property at all, use `if (!("tag_id" in product))` – Barmar Feb 14 '22 at 20:44
  • is it this? https://stackoverflow.com/questions/31626876/check-if-falsy-except-zero-in-javascript – cmgchess Feb 14 '22 at 20:45
  • `if(!product.hasOwnProperty("tage_id")) {return}` – Elabbasy00 Feb 14 '22 at 20:53
  • 1
    https://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-specific-property-in-javascript – epascarello Feb 14 '22 at 20:56
  • It's not really clear what you *want* the condition to do. What values can `product` (or `product.tag_id`) have? – Bergi Feb 14 '22 at 22:34

1 Answers1

1
if (!product.tag_id && product.tag_id !== 0) return;
// Do something else

This checks for if the product tag id is not equal to zero before returning.

Compositr
  • 717
  • 6
  • 18
  • 1
    I might add that if tag_id should be, or is a number, you could coerce it to one like +product.tag_id. Then this expression becomes more simple with product.tag_id !==0 or maybe just product.tag_id > 0 – terpinmd Feb 14 '22 at 21:07