Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

void(0) returns `undefined`, but allows property access. Why?

Tags:

javascript

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/

like image 330
Alex Wayne Avatar asked Sep 12 '13 20:09

Alex Wayne


People also ask

Is void 0 same as undefined?

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 .

What is the purpose of void 0?

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.

How do you avoid Cannot read property of undefined react?

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.

Why is an object undefined?

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).


2 Answers

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.

like image 102
Jonathan Lonowski Avatar answered Sep 26 '22 03:09

Jonathan Lonowski


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
like image 35
zs2020 Avatar answered Sep 26 '22 03:09

zs2020