JavaScript: Void Operator Explanation

The void is a operator that always returns undefined after evaluate a given expression

The void operator allows inserting expressions that produce side effects into places where an expression that evaluates to undefined is desired.

Syntax:

It is often used merely to obtain the undefined primitive value, usually using void(0) (which is equivalent to void 0). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

Examples:

The void operator can be used as follow:

1. Immediately Invoked Function Expressions (IIFE)

The void operator can be used to invoke the function imediately, that is same with Self-Executing Anonymus Functions (SEAF)

2. Avoid browser stop executing function

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:

3. JavaScript URIs

The void operator can be used to return undefined when a browser follows a javascript: URI. It evaluates the code in the URI and then replaces the contents of the page with the returned value


Resource:

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA