Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of void operator in JavaScript?

I've seen some people using void operator in their code. I have also seen this in href attributes: javascript:void(0) which doesn't seem any better than javascript:;

So, what is the justification of using the void operator?

like image 964
mkoryak Avatar asked Mar 20 '09 16:03

mkoryak


People also ask

What does void mean JavaScript?

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 use void operator?

The JavaScript, the void operator is used to explicitly return undefined. Its a unary operator, meaning only one operand can be used with it. You can use it like shown below — standalone or with a parenthesis.

When should void be used?

When used as a function return type, the void keyword specifies that the function doesn't return a value. When used for a function's parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is "universal."

How do you return a void in JavaScript?

If inserting an expression into a web page results in an unwanted effect, then use JavaScript void to remove it. Adding “javaScript:void(0)”, returns the undefined primitive value. The void operator is used to evaluate the given expression. After that, it returns undefined.


1 Answers

Explanation of its use in links:

This is the reason that bookmarklets often wrap the code inside void() or an anonymous function that doesn't return anything to stop the browser from trying to display the result of executing the bookmarklet. For example:

javascript:void(window.open("dom_spy.html")) 

If you directly use code that returns something (a new window instance in this case), the browser will end up displaying that:

javascript:window.open("dom_spy.html"); 

In Firefox the above will display:

[object Window] 
like image 95
Crescent Fresh Avatar answered Sep 18 '22 09:09

Crescent Fresh