I came across some code recently that looked like this:
1 2 3 4 5 6
While it’s definitely worthwhile to know what
undefined instead of
void 0. There are a few reasons why some might consider using this in your codebase, and I’d like to address a few of them here.
undefined and that’s potentially an argument for why
void 0 should be used instead of
undefined. Formally, the
window.undefined is similar to
window.setTimeout It is assignable in ES3, so you can change the value of undefined in old browsers. Understandably, everyone is worried about what happens if someone sneaks
undefined = true somewhere into your codebase, but there are other ways to deal with this problem.
Why not worry about the assignment problem?
undefinedproblem, by making sure that trying to assign undefined is a no-op.
- Ideally, your entire codebase should be in Strict Mode, and ES5 strict mode does not allow assigning to non-writeable properties, which will mean that an error is thrown if someone accidently assigns to
- Whatever linting tool that you use should have an option to flag accidental things like this with nice early error messages.
Depending on the developer’s programming language background, some devs feel like using
void 0 expresses their intent clearer. They want to ‘void out’ a certain property in a similar way to how programming languages like C have a
void return type if they don’t return anything. Personally, I have a hard time understanding how the word “undefined” can be better expressed considering there’s only one actual regular dictionary definition of the word, but everyone has different tastes when it comes to these things.
void 0 and I think that it only sounds better if you’re coming from C/C++.
3. The tendency to show off
void 0 does is much lower.
undefined is that alternative whenever you think you need to use
void 0. Please don’t think that I’m telling you not to use anything that’s not known by most JS devs. Getters and setters, for example, are fine because those are incredibly powerful and have no more widely known alternative.
Alternatives for the concerned
In case you are very worried about older browsers and malicious code, the way to deal with this is silo away somewhere in your code an actual unchangeable version of the value
undefined and use that where you need it. Define it once and use it everywhere instead of
void 0 everwyhere.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Please don’t use
void 0 in code that other people need to read. If you’re worried about malicious code changing the value, there are alternatives. When trying to decide about what to include in your codebase, consider what percentage of people that work with you will understand what you’re doing and apply the litmus test of ‘Is there an equivalent alternative?’.
See you in the comments or on twitter!
In case you saw my twitter poll, here’s the result breakdown: