Checking if a value exist - typeof

Hi guys,

I would like to check if a value exists. What is the difference between if (typeof x === "undefined") and if (x === undefined) ? I tried inserting both in my function and it works the same.

function isExist(x) {
  if (typeof x === "undefined") {
     return "It doesn't exist!";
  }
  return `It exists and the value is ${x}`;
}

OR

function isExist(x) {
  if (x === undefined) {
     return "It doesn't exist!";
  }
  return `It exists and the value is ${x}`;
}

It seems to be producing the same result, which one should I use?

The difference is checking the typeof is a comparison of a string like, “undefined” or “number” or “Boolean”. Checking the ‘x’'s value is just a normal comparison, like checking if it’s 0 or 1 but undefined instead. Since they will produce the same result is up to you, the second one is less typing so you should probably stick with that one

1 Like