Say something about undefined
- Dominant language
- JavaScript
- Stars
- 148k
- Forks
- 26.6k
- PR merge metrics
- No merged PRs in 30d
Description
I find people treat `undefined` incorrectly a lot. It's a value, you can use it, test for it, etc, but people frequently use `typeof x == "undefined"` when they don't need to.
I made a [fork](https://github.com/ianb/javascript) with a big changeset of my own opinions, but here's the section I wrote about undefined:
---
``````
## undefined
- `undefined` is an object. You should use it as an object. You can test for it. For instance:
```javascript
// good
function pow(a, b) {
if (b === undefined) {
b = 1;
}
return Math.pow(a, b);
}
// bad
function pow(a, b) {
if (typeof b == "undefined") {
b = 1;
}
return Math.pow(a, b);
}
```
- *Only* use `typeof x == "undefined"` when the variable (`x`) may not be declared, and it would be an error to test `x === undefined`:
```javascript
if (typeof Module == "undefined") {
Module = {};
}
// But also okay, for browser-only code:
if (window.Module === undefined) {
Module = {};
}
```
Note that you can't use `window` in Node.js; if you think your code could be used in a server context you should use the first form.
``````
Contributor guide
No contributing guide indexed for this repository
Research direction
Review the issue text and the linked fork's proposed undefined section first; no repository file or test is named. Confirm the project's preferred guidance for checking undefined, then update the relevant style-guide documentation if maintainers agree and verify that the final wording is consistent with the surrounding guidance.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100