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?
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.
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 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."
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.
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]
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