What does `void 0` mean? [duplicate]
Asked Answered
M

3

600

Reading through the Backbone.js source code, I saw this:

validObj[attr] = void 0;

What is void 0? What is the purpose of using it here?

Mareah answered 17/9, 2011 at 3:58 Comment(1)
The linked question about "void(0)" does not make it very clear that void is a special keyword with unique syntax. I had no idea that void(0) and void 0 were the same keyword until I found this question.Facial
G
1187

What does void 0 mean?

void[MDN] is a prefix keyword that takes one argument and always returns undefined.

Examples

void 0
void (0)
void "hello"
void (new Date())
//all will return undefined

What's the point of that?

It seems pretty useless, doesn't it? If it always returns undefined, what's wrong with just using undefined itself?

In a perfect world we would be able to safely just use undefined: it's much simpler and easier to understand than void 0. But in case you've never noticed before, this isn't a perfect world, especially when it comes to Javascript.

The problem with using undefined was that undefined is not a reserved word (it is actually a property of the global object [wtfjs]). That is, undefined is a permissible variable name, so you could assign a new value to it at your own caprice.

alert(undefined); //alerts "undefined"
var undefined = "new value";
alert(undefined) // alerts "new value"

Note: This is no longer a problem in any environment that supports ECMAScript 5 or newer (i.e. in practice everywhere but IE 8), which defines the undefined property of the global object as read-only (so it is only possible to shadow the variable in your own local scope). However, this information is still useful for backwards-compatibility purposes.

alert(window.hasOwnProperty('undefined')); // alerts "true"
alert(window.undefined); // alerts "undefined"
alert(undefined === window.undefined); // alerts "true"
var undefined = "new value";
alert(undefined); // alerts "new value"
alert(undefined === window.undefined); // alerts "false"

void, on the other hand, cannot be overidden. void 0 will always return undefined. undefined, on the other hand, can be whatever Mr. Javascript decides he wants it to be.

Why void 0, specifically?

Why should we use void 0? What's so special about 0? Couldn't we just as easily use 1, or 42, or 1000000 or "Hello, world!"?

And the answer is, yes, we could, and it would work just as well. The only benefit of passing in 0 instead of some other argument is that 0 is short and idiomatic.

Why is this still relevant?

Although undefined can generally be trusted in modern JavaScript environments, there is one trivial advantage of void 0: it's shorter. The difference is not enough to worry about when writing code but it can add up enough over large code bases that most code minifiers replace undefined with void 0 to reduce the number of bytes sent to the browser.

Genni answered 17/9, 2011 at 4:1 Comment(26)
@PeterOlson the main benefit of void 0 is that the 0 is the de-facto standard for using void to generate an undefined value.Perpend
First, undefined is not a keyword, it's just a property of the global object. Second, in ECMAScript5, it is write protected, so the void 0 trick is only neccessary if someone uses undefined as a local variable within a function.Coccidioidomycosis
@Pumbaa80 Unless you use strict mode, the trick is necessary because most browsers allow undefined to be mutated.Genni
but why does it need a parameter? any useful examples of voiding an expression? why void 0? and not void 1?Schaaff
@AntonN There might be some possible use cases where you want to execute a function that has side effects but ignore the return value.Genni
So this is basically the same as if (typeof options.something === 'undefined') which I previously remembered from SO being the safe pattern for checking for undefinedness?Hernia
@Hernia Not really, void x always returns undefined. typeof x === "undefined" checks if x is undefined.Genni
Another common pattern is to provide undefined as an argument in an immediate function: (function(undefined){ ... }()) Which is specially useful for minification.Respective
Which JS engine will allow undefined's value to be changed?Molliemollify
@RobertCambridge I think it's required by the ES5 spec, so it should be allowed by most JS engines.Genni
Interesting that current versions of Chrome and Firefox don't then! :)Molliemollify
That same code alerts undefined when pasted into the console. I've seen odd things happen in the console, can't remember why or where I read about it though! Good to know.Molliemollify
@PeterOlson, in the example you're showing, you're creating a new local variable that hides the global one. The global undefined cannot be reassigned. The issue appears to be that undefined is not a reserved keyword. Try your fiddle again without the var prefix, making it an assignment rather than a declaration.Manzoni
@RobertCambridge, see my prior comment for a clarification about why it doesn't work in Chrome's console. The original fiddle was hiding the global with a local. I agree with you that undefined cannot be reassigned in current Chrome or Firefox versions.Manzoni
@DrewNoakes It's not a local variable, because I defined it in global scope. You are right, though, that the problem is not that undefined is changing, but that a variable is shadowing it.Genni
@PeterOlson, it is a local variable in the jsFiddle you linked to, as jsFiddle wraps the code in a function, ala: window.onload = function() { var undefined = 4; alert(undefined); }. Attempting to shadow the global on Chrome, Firefox and Node.JS doesn't seem to work for me.Manzoni
It seems like void undefined would be slightly clearer than void 0, no?Greenockite
@Greenockite It would work just as well, but it's longer and possibly more confusing because void 0 is a widely-known Javascript idiom whereas void undefined is less common and might cause people to think a little bit more about it.Genni
@PeterOlson Yeah, you're probably right. As you can imagine I ended up on this thread because I hadn't seen void 0 before, but now that I have, I agree with your reasoning.Greenockite
ok, so why void 0 and not just void?Dvorak
@Dvorak Because void requires an argument, so using it without anything after it would be a syntax error.Genni
@PeterOlson yes, this I know, but I mean, WHY does void require an argument, since it doesn't matter what you pass to it?Dvorak
@Dvorak That's a question for the language designers; I don't knowGenni
Makes sense what you said in your answer, but what I don't understand, is why the void keyword takes an argument? It returns undefined anyway, so why not just leave it as return void and nothing more?Bayern
Fun fact: because "undefined" can be a variable name, you can get ReferenceErrors in this case: (() => {'use strict';alert(undefined);let undefined = 2;}()) (because "undefined" refers to the local variable in the next line, not the global property).Valois
the old pattern typeof myVar === 'undefined' has the advantage of not throwing a ReferenceError in console where as myVar === void 0 does, so can someone tell me why i should not keep using the old way for the "extra layer of safety" if they are otherwise functionally equivalent?Vaporetto
W
128

void 0 returns undefined and can not be overwritten while undefined can be overwritten.

var undefined = "HAHA";
Wheel answered 17/9, 2011 at 4:20 Comment(5)
ECMAScript 5 defines undefined as read-onlyIoneionesco
@licancabur: I believe that is in strict-mode code only, yes?Schlenger
Wow, I keep getting downvotes on this. When this was posted 3 years ago, browsers allowed you to set undefined to any value.Wheel
If an answer becomes redundant over time why should it not be downvoted in favour of a more up-to-date answer?Neptunium
@epascarello, Although what you wrote there is correct (somehow), but I don't think it is answering the question (clear enough) that is asking what does that mean.Nahshu
A
42

void is a reserved JavaScript keyword. It evaluates the expression and always returns undefined.

Ailssa answered 17/9, 2011 at 4:0 Comment(1)
It's probably shorter than undefined, and also is guaranteed to return it (unlike the global overwriteable undefined).Ailssa

© 2022 - 2024 — McMap. All rights reserved.