void operator in JavaScript
In JavaScript, void is a unary operator that evaluates an expression and returns undefined. It is primarily used to ensure that an expression evaluates to undefined regardless of the original value or side effects of the expression.
Syntax
void expressionCommon Uses of void
-
Ensuring
undefinedReturn Value: Usingvoidcan be useful in contexts where you need an expression to explicitly returnundefined. For example:undefined = 3; void 0; // returns undefined void (0); // returns undefined void "hello"; // returns undefined -
Bookmarklets: In JavaScript bookmarklets (small JavaScript programs stored as a URL), using
voidcan prevent the browser from navigating to a new URL when the code is executed. Try this in your browser’s address bar:javascript:void(alert('Hello, World!')); -
Self-invoking Functions:
voidcan be used with self-invoking functions (Immediately Invoked Function Expressions or IIFEs) to ensure they returnundefined:> void (function() { return 1; })() undefined > (function() { return 1; })() 1 -
Avoiding JavaScript Engine Optimization Issues: In rare cases,
voidis used to prevent JavaScript engines from applying certain optimizations that could cause unexpected behavior, although this is more of a historical artifact and not common practice today.