Get AI Code Completions for Your IDE

Home   >   Tutorials   >   JavaScript   >   How to Use the void operator in JvaScript

JavaScript - How to Use the void operator in JvaScript

The void operator evaluates a given expression and then returns undefined.

If void operates on an expression which produces a value it will always return undefined. For example

console.log(void 2); // Expected output: undefined

In the examples above, undefined is returned for a value of type Number.

The next example applies the void operator to an undeclared variable.

console.log(void undeclared); 
// Expected output: Uncaught ReferenceError: undeclared is not defined

In the case of “undeclared”, this variable was not declared, therefore, it does not produce a value and void cannot operate on it. The return output is an Uncaught ReferenceError.

Usage

The void operator is typically used in two cases in JavaScript:

  1. To modify JavaScript URIs and prevent a page refresh (commonly used as void(0)).
  2. Immediately Invoked Function Expressions.

We explore each case in detail below.

JavaScript URIs

You might have encountered the void operator in HTML documents as a value for an href attribute of an anchor tag (<a>).

Usually, the value provided for an href attribute in an anchor tag is a URL that specifies the location to which the user will be directed upon a click.

When using the href attribute, the anchor tag gets a customized design – that of a hyperlink. The text for the link is given a blue color, is underlined, and the mouse cursor automatically converts to a pointer when hovering over the link. (Note – all of this is very simple to achieve with basic CSS as well).

Clicking an anchor tag with an href attribute has a side effect – it causes the page to refresh. When you redirect to a different page, this might be the desired behavior, but if you wish to remain on the same spot on the same page, the automated refresh might become a nuisance.

For example, let us say you wish to get a user’s feedback after reading an article.

HTML

<a href="" onclick="prompt('Was this article helpful? Please share your thoughts')">Help us improve</a>

At the end of the supposed article, the anchor will appear as a line of text reading “Help us improve”. This is specified via the anchor tag in the HTML document, with an empty string provided for the href attribute.

After the reply is submitted, the page will refresh. This results in all unsaved data being lost, and the user is sent back to the top of the page.

This has side effects for the page’s JavaScript as well as its user experience. For example, try adding the following JavaScript code to an HTML document:

JavaScript

let count = 0;
const counter = setInterval(() => {
    count++;
    console.log('count: ', count);
}, 1000);

This code will update the variable count every second, incrementing its value and printing the current value to the console.

After the reply is submitted by the user, the page will refresh and let count will be equal to zero again, resetting the calculation results.

Using a hash (#) instead of an empty string for the href value will not prevent this from happening, but using the void operator will.

Anchor tag href attribute with void operator

Below is an example of using the void operator in an HTML anchor tag:

HTML

<a href="javascript:void(0)" onclick="prompt('Was this article helpful? Please share your thoughts?')">Help us improve</a>

The sample code above, by using the void operator, prevents the page refresh and allows the count to continue – no data is lost as the page does not refresh.

void(0) is a convention. It is the same as void 0 without parentheses. Actually, any expression which produces a value will do (e.g. void null). The key is that the value of href must be set to undefined. As href only accepts String literals, using javascript:void(0) is an easy way to send this value to the href attribute.

Tip: It is better to use CSS instead of “javascript:void(0)” wherever you can.

 

Immediately Invoked Function Expressions

The syntax for Immediately Invoked Function Expressions (IIFEs) usually includes encasing the function in parentheses, as we see below:

(function iife() {
    console.log('Done!');
})();
// Expected output: Done!

For more about IIFEs follow this link.

Omitting the enveloping parentheses will lead to an Uncaught SyntaxError.

function iife() {
    console.log('Done!');
}();
// Expected output: Uncaught SyntaxError

The void operator solves this issue by treating the function keyword as an expression instead of a declaration. This resolves the syntax error, and allows the function to be immediately executed:

void function iife() {
    console.log("Done!");
}();
// Expected output: Done!

Tip: It is often better to use the common syntax for IIFEs in order to prevent confusion.

 

Related Articles

JavaScript – How to use functions

JavaScript – How to Use setTimeout

JavaScript – How to use jQuery Promise

Get AI Code Completions for Your IDE