So void
returns undefined
after executing the expression passed to it. undefined
throws exceptions when you try to access its properties. So why is that void(0).prop
returns undefined
instead of crashing?
alert("void(0) => " + void(0)); // undefined
// How is it that this doesn't throw an exception?
alert("void(0).someprop => " + void(0).someprop); // undefined
// Exception, can't access property of undefined.
alert("undefined.someprop => " + undefined.someprop); // crash
http://jsfiddle.net/bFhLS/
In JavaScript code, especially in older legacy code, you sometimes find the expression void 0 . The void operator evaluates an expression and returns the primitive value undefined. void 0 evaluates 0 , which does nothing, and then returns undefined . It is effectively an alias for undefined .
JavaScript void 0 means returning undefined (void) as a primitive value. You might come across the term “JavaScript:void(0)” while going through HTML documents. It is used to prevent any side effects caused while inserting an expression in a web page.
To solve the "Cannot read properties of undefined" error, make sure that the DOM element you are accessing exists. The error is often thrown when trying to access a property at a non-existent index after using the getElementsByClassName() method.
undefined means that the variable value has not been defined; it is not known what the value is. null means that the variable value is defined and set to null (has no value).
The void
operator doesn't use parenthesis itself. So, the statement is probably being parsed as:
void( (0).someprop )
And accessing someprop
from the Number
. Rather than as:
(void (0)).someprop
As you were probably expecting, which does throw an error.
void
is an operator, it is NOT a function.
void(0)
is equivalent to "void 0"
.
So void(0).someprop
is equivalent to void 0..someprop
.
To prove,
void(undefined).someprop
throws an error, since it will be evaluated as (someprop
doesn't exist in undefined
for sure)
void undefined.someprop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With