Learnitweb

void operator in JavaScript

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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let result = void 0;
console.log(result); // undefined
let result = void 0; console.log(result); // undefined
let result = void 0;
console.log(result); // undefined

2. Syntax

The syntax of using void operator is:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
void expression
void expression
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).

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
console.log(void (0)); // undefined
console.log(void (0)); // undefined
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
void (function iife() {
console.log("hello");
})();
// hello
void (function iife() { console.log("hello"); })(); // hello
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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>
<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>
<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>