Why does `typeof undefined` return “undefined” and is it still useful today?

0
0
Asked By CuriousCoder88 On

I've been curious about the behavior of `typeof undefined`, specifically why it returns "undefined" and if there's any practical use case for this in modern JavaScript. I've noticed that older code often includes checks like `if (typeof myVar === "undefined")`, but with the introduction of `let`, `const`, and nullish coalescing, it seems a bit outdated. Is there still a valid reason to use `typeof undefined` comparisons today, or is this just a quirk we've learned to live with?

3 Answers

Answered By JSNinja34 On

If you need a strict check, `typeof` can be really useful! For example, when checking properties in an object, like `if (obj.myProp)`, you want to avoid false positives from falsy values like `0`. Using `typeof` can confirm whether the property exists: `if (typeof obj.myProp !== "undefined" && obj.myProp !== null)`. It helps you avoid unexpected behavior especially when you're not just looking for truthy values.

Answered By TechWhiz42 On

`typeof` needs to return something for `undefined`, so if you're wondering what else it could return, that's an interesting thought! In the past, when `undefined` could be changed, `typeof` checks were super handy. These days, though, a simple `value === undefined` usually does the trick, or you could use `==` to check for both `null` and `undefined`. But yeah, sometimes you just want to confirm if a value is `undefined`, and `typeof` is reliable for that.

CodeGuru21 -

Isn't it the other way around? `value == null` also checks for `undefined`, right?

Answered By DevDude99 On

Using `typeof` is great for checking if a variable is in scope without throwing an error. For example, if you check something that doesn't exist like `doesNotExist`, it would throw a ReferenceError. But `if (typeof doesNotExist !== "undefined")` avoids that error entirely. Just keep in mind that it doesn’t tell you if a variable is just `undefined` versus not defined at all, so it's not perfect for all cases.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.