Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use of if(typeof value !== 'undefined')? #236

Closed
Fdawgs opened this issue Oct 18, 2023 · 3 comments · Fixed by #238
Closed

Use of if(typeof value !== 'undefined')? #236

Fdawgs opened this issue Oct 18, 2023 · 3 comments · Fixed by #238

Comments

@Fdawgs
Copy link
Member

Fdawgs commented Oct 18, 2023

Noticed this in a few places in this repo:

https://github.com/fastify/fastify-helmet/blob/b0aacaee932e1629a6233c97424d739735b3293c/index.js#L25C31-L25C31

Never seen this before, does this have a performance benefit over the following?:

  • if(value)
  • if(value !== undefined)
@Uzlopak
Copy link
Contributor

Uzlopak commented Oct 18, 2023

More like differenciating between null and undefined.

@gurgunday
Copy link
Member

gurgunday commented Oct 18, 2023

Now, this is a little nuanced

In nearly all cases, we should definitely prefer value === undefined to typeof value === “undefined” as checking against undefined is simply faster

However, there are times where you want to check if a top level variable even exists in the first place

For example, to check if variable b exists at the most outer scope, you can't use if(b !== undefined) {} because it will throw a ReferenceError when b isn't defined

For that, if(typeof b !== 'undefined') {} must be used. The typeof operator will silence the error and just return 'undefined'

So, it'd be great if you could find a way to create a script that mass updates the repos and we reviewed them one by one to see if the typeof use is indeed redundant 😁

@Fdawgs
Copy link
Member Author

Fdawgs commented Oct 28, 2023

@gurgunday will make PRs and point them back to this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants