1. Introduction
Sometimes the requirement is to evaluate an expression that produces a value at a place where the expected result is undefined
. Or simply to say, you want to evaluate an expression and result as undefined
, the void
operator can be used in such case. The void
operator evaluates the given expression and then returns undefined
.
The void
operator is usually used to obtain the primitive value undefined
.
let result = void 0; console.log(result); // undefined
2. Syntax
The syntax of using void
operator is:
void expression
3. void(0)
As mentioned earlier, void
operator is usually used to get the primitive value undefined
. The commonly used approach is void(0)
.
console.log(void (0)); // undefined
4. void with Immediately Invoked Function Expressions
When used with immediately-invoked function expression, void
makes it as an expression instead a declaration.
void (function iife() { console.log("hello"); })(); // hello
5. void in href value
When javascript:expression
is encountered, the browser evaluates the expression and replaces the content of the page with the value of expression. If the result of expression is undefined
then it does nothing.
For example, if you want to create an anchor tag when clicked does nothing, you can use void
operator.
<html> <body> <ul> <li> <a href="javascript:void(0);"> Clicking here will not do anything </a> </li> <li> <a href="javascript:void(document.body.style.backgroundColor='red');"> Change background to red</a> </li> </ul> </body> </html>